﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="GBK">
    <title>Excel Ai Chat Content</title>
<!-- 先加载核心库 -->
<script src="https://officeai.local/js/highlight.min.js"></script>
<link rel="stylesheet" href="https://officeai.local/css/github.min.css">
<script src="https://officeai.local/js/marked.min.js"></script>
<script src="https://officeai.local/js/vbscript.min.js"></script>

    <script>
        hljs.registerAliases('vba', { languageName: 'vbscript' });
        hljs.highlightAll();
    </script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            line-height: 1.5;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f9f9f9;
            padding-bottom: 160px;
        }

        #chat-output {
            /* white-space: pre-wrap; */
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        pre {
            position: relative;
            margin: 1em 0;
            border-radius: 6px;
            background-color: #f6f8fa;
            overflow: hidden;
        }

            pre code {
                display: block;
                padding: 12px;
                overflow-x: auto;
                font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
                font-size: 13px;
                line-height: 1.4;
            }

        .code-buttons {
            display: flex;
            justify-content: flex-start;
            padding: 4px 8px;
            background-color: #f0f0f0;
            border-top: 1px solid #ddd;
        }

        .code-button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 4px 8px;
            margin-left: 6px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.2s;
            display: flex;
            align-items: center;
        }

            .code-button:hover {
                background-color: #45a049;
            }

            .code-button svg {
                margin-right: 4px;
                width: 14px;
                height: 14px;
            }

        .edit-button {
            background-color: #FF9800;
        }

            .edit-button:hover {
                background-color: #F57C00;
            }

        .execute-button {
            background-color: #2196F3;
        }

            .execute-button:hover {
                background-color: #0b7dda;
            }

        .code-editor {
            width: 100%;
            min-height: 100px;
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
            font-size: 13px;
            line-height: 1.4;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            resize: vertical;
        }

        .editor-buttons {
            display: flex;
            justify-content: flex-start;
            margin-top: 8px;
            margin-bottom: 20px;
        }

        p {
            margin: 0.5em 0;
        }

        /* 发起人信息样式 */
        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            font-size: 14px;
            color: #555;
        }

        .avatar-ai {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #4a6fa5;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
            font-size: 12px;
        }

        .sender-name {
            font-weight: 500;
            margin-right: 8px;
        }

        .timestamp {
            color: #888;
            font-size: 12px;
        }

        .sender-info {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }

        .message-content {
            margin-left: 32px;
        }

        .chat-container {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e6e6e6;
        }

        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .avatar-me {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #39b362;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
            font-size: 12px;
        }

        .sender-name {
            font-weight: 500;
            margin-right: 10px;
        }

        .timestamp {
            color: #888;
            font-size: 12px;
        }

        .reasoning-container {
            margin: 0 0 15px 42px;
            border-radius: 8px;
            background-color: #f8f9fa;
            overflow: hidden;
            transition: all 0.3s ease;
            max-height: 500px;
            border: 1px solid #e0e5eb;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }

            .reasoning-container.collapsed {
                max-height: 38px;
            }

        .reasoning-header {
            padding: 8px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #edf2f7;
            cursor: pointer;
            user-select: none;
            border-bottom: 1px solid #e0e5eb;
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .reasoning-title {
            font-weight: 500;
            color: #4a6fa5;
            display: flex;
            align-items: center;
        }

            .reasoning-title svg {
                width: 16px;
                height: 16px;
                margin-right: 6px;
                fill: #4a6fa5;
            }

        .reasoning-toggle svg {
            width: 16px;
            height: 16px;
            fill: #4a6fa5;
            transition: transform 0.2s ease;
        }

        .collapsed .reasoning-toggle svg {
            transform: rotate(-90deg);
        }

        .reasoning-content {
            padding: 12px 15px;
            font-size: 0.9em;
            color: #444;
            line-height: 1.5;
            overflow-wrap: break-word;
            background-color: #f8f9fa;
            max-height: none;
            overflow-y: auto;
        }

        .collapsed .reasoning-content {
            display: none;
        }

        .message-content {
            margin-left: 42px;
            line-height: 1.6;
        }

        /* 代码块样式优化 */
        pre {
            background-color: #f6f8fa;
            border-radius: 6px;
            padding: 12px;
            overflow: auto;
        }

        code {
            font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
            font-size: 0.9em;
        }

        .code-toggle-label {
            cursor: pointer;
            color: #4a6fa5;
            padding: 4px 8px;
            font-size: 12px;
            background: #edf2f7;
            border-radius: 4px 4px 0 0;
            border: 1px solid #e0e5eb;
            border-bottom: none;
            margin-top: 10px;
        }

        .code-toggle-label:hover {
            background: #e3eaf3;
        }

        pre.collapsible {
            margin-top: 0;
            transition: max-height 0.3s ease-out;
/*            max-height: 500px;*/
            overflow: hidden;
        }

        pre.collapsible.collapsed {
            max-height: 0;
            margin-bottom: 10px;
        }

        .code-block {
            margin-top: -1px; /* 确保和toggle-label无缝衔接 */
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        .reasoning-content, .message-content {
            animation: fadeIn 0.3s ease-in-out;
        }

        /* 当内容超过一定高度时自动调整容器高度 */
        .reasoning-container:not(.collapsed) {
            display: flex;
            flex-direction: column;
            max-height: 80vh;
        }

        .reasoning-content {
            flex-grow: 1;
        }

        #case-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
            overflow: hidden;
            border: 1px solid #e6e6e6;
        }

        #case-header {
            background: linear-gradient(135deg, #4a6fa5 0%, #3d5a7c 100%);
            padding: 5px 25px;
            color: white;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

            #case-header h2 {
                margin: 0;
                font-size: 1.3em;
                font-weight: 400;
                letter-spacing: 0.5px;
            }

        #case-content {
            padding: 10px;
        }

        #case-info {
            color: #444;
            line-height: 1.3;
        }

            #case-info p {
                margin: 10px 0;
                font-size: 0.75em;
                display: flex;
                align-items: flex-start;
            }

                #case-info p:before {
                    color: #4a6fa5;
                    font-weight: bold;
                    margin-right: 10px;
                    margin-top: 2px;
                }

            #case-info a {
                color: #4a6fa5;
                text-decoration: none;
                font-weight: 500;
                position: relative;
                transition: all 0.2s ease;
                padding: 0 2px;
            }

                #case-info a:hover {
                    color: #3d5a7c;
                    text-decoration: none;
                }

                #case-info a:after {
                    content: '';
                    position: absolute;
                    width: 100%;
                    height: 1px;
                    bottom: -1px;
                    left: 0;
                    background-color: #4a6fa5;
                    transform: scaleX(0);
                    transform-origin: right;
                    transition: transform 0.3s ease;
                }

                #case-info a:hover:after {
                    transform: scaleX(1);
                    transform-origin: left;
                }

        #version {
            background: #f0f4f8;
            padding: 1px 6px;
            border-radius: 4px;
            font-size: 0.8em;
            color: #4a6fa5;
            font-weight: 500;
        }

        #chat-input-card {
            position: sticky;
            width: 100%;
            bottom: 0;
            background: #fff;
            box-shadow: 0 -2px 12px rgba(0,0,0,0.06);
            border-radius: 12px;
            padding: 12px 16px 8px 16px;
            z-index: 100;
        }

        #chat-input-inner {
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        /* 提示词建议样式 */
        #prompt-suggestions {
            border: 1px solid #e0e0e0;
            border-bottom: none; /* 避免与textarea上边框重复 */
            border-radius: 6px 6px 0 0;
            max-height: 150px;
            overflow-y: auto;
            background-color: #fff;
        }

        .prompt-suggestion-item {
            padding: 8px 12px;
            cursor: pointer;
            font-size: 14px;
            color: #333;
            border-bottom: 1px solid #f0f0f0;
        }

        .prompt-suggestion-item:last-child {
            border-bottom: none;
        }

        .prompt-suggestion-item:hover {
            background-color: #f9f9f9;
        }
        #chat-input {
            width: 100%;
            min-height: 38px;
            max-height: 120px;
            resize: none;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 15px;
            padding: 8px 12px;
            box-sizing: border-box;
            font-family: inherit;
            outline: none;
            transition: border 0.2s;
        }

            #chat-input:focus {
                border: 1.5px solid #4a6fa5;
            }

        #chat-input-actions {
            width: 100%;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 2px;
        }

        #send-button {
            background: rgb(175 184 191);
            border: none;
            border-radius: 6px;
            padding: 2px 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: background 0.2s;
        }

            #send-button:hover {
                background: #688ec5;
            }

        .input-option {
            display: flex;
            align-items: center;
            gap: 3px;
            font-size: 13px;
            color: #555;
        }

        #ai_model_select {
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 13px;
            background: #fafbfc;
        }

        @media (max-width: 600px) {
            #chat-input-card {
                max-width: 100%;
                padding: 8px 4px 4px 4px;
            }
        }

        #chat-bottom-bar {
            position: fixed;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: 200;
            background: #fff;
            box-shadow: 0 -2px 12px rgba(0,0,0,0.06);
            display: flex;
            flex-direction: column;
            align-items: stretch;
            padding: 0 16px 8px 16px;
            box-sizing: border-box;
            margin-left: auto;
            margin-right: auto;
            width: 100%;
        }

        @media (min-width: 832px) {
            #chat-bottom-bar {
                left: 50%;
                transform: translateX(-50%);
                width: 800px;
                max-width: 100vw;
                padding-left: 0;
                padding-right: 0;
            }
        }
        #references-wrapper {
            width: 100%;
            background: #f8f9fa; /* 浅灰色背景，使其与输入区域略有区分 */
            border-radius: 8px; /* 圆角与输入框协调 */
            padding: 8px 12px; /* 内部留白 */
            box-shadow: 0 1px 3px rgba(0,0,0,0.05); /* 轻微阴影增加层次感 */
            margin-bottom: 8px; /* 与下方元素的间距 */
            box-sizing: border-box;
        }

        /* 引用区域标题 ("引用:") */
        .reference-section-title { /* 此类名已在HTML中指定给新的 span#references-title */
            font-size: 13px; /* 稍微增大字号 */
            color: #333; /* 深灰色，更清晰 */
            margin-bottom: 8px; /* 标题与芯片之间的间距 */
            display: block;
            font-weight: 500;
        }

        /* 包含所有引用项 (chips) 的容器 */
        .reference-chips-container { /* 此类名已在HTML中指定给新的 div#reference-chips-list */
            max-height: 70px; /* 调整最大高度以适应内容 */
            overflow-y: auto;
            width: 100%;
            line-height: 0;
            padding-top: 2px;
        }

        /* 单个引用项 (chip) */
        .reference-chip {
            display: inline-block;
            vertical-align: top;
            background-color: #e9ecef; /* 调整chip背景色 */
            border: 1px solid #ced4da; /* 调整chip边框色 */
            border-radius: 16px;
            padding: 4px 10px 5px 10px; /* 微调内边距 */
            font-size: 12px; /* 调整字体大小 */
            color: #212529; /* 调整文字颜色 */
            box-shadow: none; /* 移除单个chip的阴影，由外部wrapper统一处理 */
            transition: background-color 0.2s, border-color 0.2s;
            margin-right: 6px;
            margin-bottom: 6px;
            line-height: normal;
            max-width: 230px; /* 限制单个chip的最大宽度 */
            cursor: default; /* 默认光标 */
        }

        .reference-chip:hover {
            background-color: #dee2e6; /* hover时颜色加深 */
            border-color: #adb5bd;
        }

        .reference-chip-content-wrapper {
            display: flex;
            align-items: center;
        }

        .reference-chip-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 8px;
            flex-grow: 1; /* Allows name to take space if content-wrapper is flex */
            min-width: 0; /* Helps with ellipsis in flex item */
        }

        .reference-chip-remove {
            cursor: pointer;
            color: #6c757d; /* 移除按钮颜色调整 */
            font-size: 15px;
            border: none;
            background: none;
            outline: none;
            display: flex;
            align-items: center;
            padding: 0;
            flex-shrink: 0;
            transition: color 0.2s;
        }

        .reference-chip-remove:hover {
            color: #343a40; /* hover时移除按钮颜色加深 */
        }
        .reference-chip-remove svg {
            width: 16px;
            height: 16px;
            fill: currentColor; /* 使SVG颜色随父元素color属性变化 */
        }

        .reference-container {
/*            margin: 8px 0 0 42px;*/
            background: #f8fafc;
            border-radius: 8px;
            border: 1px solid #e0e5eb;
            box-shadow: 0 1px 3px rgba(0,0,0,0.04);
            overflow: hidden;
            transition: max-height 0.2s;
            max-width: 90%;
        }

        .reference-header {
            display: flex;
            align-items: center;
            cursor: pointer;
            padding: 6px 12px;
            background: #eaf1fb;
            user-select: none;
        }

        .reference-arrow {
            display: inline-block;
            transition: transform 0.2s;
            margin-right: 6px;
        }

        .reference-container:not(.collapsed) .reference-arrow {
            transform: rotate(90deg);
        }

        .reference-content {
            padding: 8px 16px;
            display: block;
            font-size: 13px;
            color: #3a4a6b;
        }

        .reference-container.collapsed .reference-content {
            display: none;
        }

        .reference-item {
            margin-bottom: 4px;
            color: #2b4a8a;
        }
        #chatMode {
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 13px;
            background: #fafbfc;
            color: #555;
            cursor: pointer;
            outline: none;
        }

        #chatMode:hover {
            border-color: #4a6fa5;
        }

        #chatMode:focus {
            border-color: #4a6fa5;
            box-shadow: 0 0 0 2px rgba(74, 111, 165, 0.1);
        }

        #stop-button {
            background: #e9525f !important;
            border: none;
            border-radius: 6px;
            padding: 6px;
            cursor: pointer;
            display: none !important;
            align-items: center;
            justify-content: center;
            transition: background-color 0.2s;
            color: white;
        }

        #stop-button:hover {
            background: #c82333;
        }
        #stop-button svg {
            display: block;
        }
        .message-footer {
            margin-left: 42px;
            margin-top: 8px;
            font-size: 12px;
            color: #888;
            display: flex;
/*            justify-content: flex-end;*/
        }

        .token-count {
            background: #f0f4f8;
            padding: 2px 6px;
            border-radius: 4px;
            color: #4a6fa5;
        }

        /* 设置按钮样式 */
        #settings-button {
            background: none;
            border: none;
            padding: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            transition: color 0.2s;
        }

            #settings-button:hover {
                color: #4a6fa5;
            }

        /* 设置dialog对话框样式 */
        .settings-dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            width: 300px;
            z-index: 1000;
        }

        .settings-title {
            font-size: 18px;
            font-weight: 500;
            margin-bottom: 2px;
            color: #333;
        }

        .setting-item {
            margin-bottom: 6px;
        }

        .setting-item.checkbox-item {
            display: block; /* 改为块级显示而不是 flex */
        }

        .setting-item.checkbox-item .setting-label {
            display: inline-block;
/*            margin-bottom: 4px;*/
        }

        .setting-item.checkbox-item .setting-tip {
            display: block;
/*            margin-top: 4px;*/
            color: #666;
            font-size: 12px;
        }

        .setting-label {
            display: block;
            font-weight: 500;
/*            margin-bottom: 4px;*/
            color: #333;
        }

        .setting-tip {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }

        .slider-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .slider {
            flex-grow: 1;
            height: 4px;
            -webkit-appearance: none;
            background: #e0e0e0;
            border-radius: 2px;
            outline: none;
        }

            .slider::-webkit-slider-thumb {
                -webkit-appearance: none;
                width: 16px;
                height: 16px;
                border-radius: 50%;
                background: #4a6fa5;
                cursor: pointer;
                transition: background .15s ease-in-out;
            }

                .slider::-webkit-slider-thumb:hover {
                    background: #3d5a7c;
                }

        .slider-value {
            min-width: 40px;
            text-align: center;
            font-size: 14px;
            color: #666;
        }

        .settings-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .settings-button {
            padding: 6px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.2s;
        }

        .cancel-button {
            background: #f5f5f5;
            color: #333;
        }

            .cancel-button:hover {
                background: #e0e0e0;
            }

        .save-button {
            background: #4a6fa5;
            color: white;
        }

            .save-button:hover {
                background: #3d5a7c;
            }

        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 999;
        }

        /**附件显示区域*/
        #chat-input-actions button {
            background: none;
            border: none;
            padding: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            transition: color 0.2s, background-color 0.2s;
        }

        #chat-input-actions button:hover {
            color: #4a6fa5;
            background-color: #f0f0f0;
        }

        #send-button { /* Specific override if needed, or adjust general style */
            background: rgb(175 184 191);
            border-radius: 6px;
            padding: 2px 8px; /* Keep your original send button padding */
            color: white; /* Assuming send button icon was white */
        }

        #send-button:hover {
            background: #688ec5;
        }

        #stop-button {
            background: #e9525f;
            padding: 6px; 
            border-radius: 6px;
            color: white; 
        }

        #stop-button:hover {
            background: #c82333;
        }

        #chat-input-actions button#attach-file-button {
            padding: 4px;
        }

        /* 附件显示区域样式 */
        #attached-files-list .attached-file-item {
            display: none !important;
            justify-content: space-between;
            align-items: center;
            background-color: #f0f4fa;
            border: 1px solid #d0d8e8;
            border-radius: 4px;
            padding: 3px 8px;
            font-size: 12px;
            color: #3a4a6b;
        }

        #attached-files-list .attached-file-name {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 8px;
        }

        #attached-files-list .remove-attached-file {
            cursor: pointer;
            color: #b71c1c;
            font-size: 14px;
            background: none;
            border: none;
            padding: 0;
        }

        #attached-files-list .remove-attached-file svg {
            width: 14px;
            height: 14px;
            fill: #b71c1c;
        }

        /**聊天内容引用的逻辑*/
        .chat-message-references {
            margin-top: 10px;
            border: 1px solid #e0e5eb;
            border-radius: 6px;
            background-color: #f8f9fa;
            overflow: hidden;
        }

        .chat-message-reference-header {
            display: flex;
            align-items: center;
            padding: 6px 10px;
            cursor: pointer;
            background-color: #edf2f7;
            user-select: none;
            border-bottom: 1px solid #e0e5eb;
        }

        .chat-message-references.collapsed .chat-message-reference-header {
            border-bottom: none; /* No bottom border when collapsed */
        }

        .chat-message-reference-arrow {
            display: inline-block;
            transition: transform 0.2s ease-in-out;
            margin-right: 8px;
            font-size: 10px; /* Smaller arrow */
            color: #4a6fa5;
        }

        .chat-message-references.collapsed .chat-message-reference-arrow {
            transform: rotate(-90deg);
        }

        .chat-message-references:not(.collapsed) .chat-message-reference-arrow {
            transform: rotate(0deg); /* Pointing down when expanded */
        }


        .chat-message-reference-label {
            font-weight: 500;
            font-size: 13px;
            color: #4a6fa5;
        }

        .chat-message-reference-content {
            padding: 8px 12px;
            font-size: 12px;
            color: #333;
            line-height: 1.5;
            max-height: 200px; /* Limit height when expanded */
            overflow-y: auto;
        }

        .chat-message-references.collapsed .chat-message-reference-content {
            display: none;
        }

        .chat-message-reference-content div { /* Each item in the content */
            margin-bottom: 4px;
            word-break: break-all; /* Break long file names or paths */
        }

        .chat-message-reference-content div:last-child {
            margin-bottom: 0;
        }

        /* 历史记录侧边栏样式 */
        #history-sidebar {
            position: fixed;
            top: 0;
            left: 0;
            width: 320px;
            height: 100vh;
            background: white;
            box-shadow: 2px 0 15px rgba(0,0,0,0.1);
            transform: translateX(-100%);
            transition: transform 0.3s ease;
            z-index: 1000;
            display: flex;
            flex-direction: column;
        }

            #history-sidebar.sidebar-visible {
                transform: translateX(0);
            }

        .sidebar-header {
            padding: 10px;
            border-bottom: 1px solid #e6e6e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: #f8f9fa;
        }

            .sidebar-header h3 {
                margin: 0;
                color: #333;
                font-size: 16px;
                font-weight: 500;
            }

        #close-sidebar-btn {
            background: none;
            border: none;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 4px;
            transition: background-color 0.2s;
        }

            #close-sidebar-btn:hover {
                background: #e9ecef;
                color: #333;
            }

        .sidebar-content {
            flex: 1;
            overflow-y: auto;
            padding: 0;
        }

        #history-list {
            padding: 0;
        }

        .history-item {
            padding: 12px 20px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: background-color 0.2s;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

            .history-item:hover {
                background: #f8f9fa;
            }

            .history-item:last-child {
                border-bottom: none;
            }

        .history-item-title {
            font-size: 14px;
            color: #333;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .history-item-date {
            font-size: 12px;
            color: #666;
        }

        .history-item-size {
            font-size: 11px;
            color: #999;
        }

        /* 遮罩层 */
        #sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(0,0,0,0.5);
            z-index: 999;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

            #sidebar-overlay.overlay-visible {
                opacity: 1;
                visibility: visible;
            }

        /* 空状态样式 */
        .empty-state {
            padding: 40px 20px;
            text-align: center;
            color: #666;
        }

        .empty-state-icon {
            font-size: 48px;
            color: #ccc;
            margin-bottom: 16px;
        }

        .empty-state-text {
            font-size: 14px;
            line-height: 1.5;
        }

        /* 加载状态 */
        .loading-state {
            padding: 20px;
            text-align: center;
            color: #666;
            font-size: 14px;
        }

        /* 历史记录按钮样式 - 与其他按钮保持一致 */
        #history-toggle-btn {
            background: none;
            border: none;
            padding: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
            transition: color 0.2s, background-color 0.2s;
        }

            #history-toggle-btn:hover {
                color: #4a6fa5;
                background-color: #f0f0f0;
            }

        /* 响应式调整 */
        @media (max-width: 768px) {
            #history-sidebar {
                width: 280px;
            }
        }

        /* MCP 按钮样式 */
        #mcp-toggle-btn {
            background: none;
            border: none;
            padding: 4px;
            cursor: pointer;
            display: none; /* 默认隐藏，检测到支持时显示 */
            align-items: center;
            justify-content: center;
            color: #666;
            transition: color 0.2s, background-color 0.2s;
        }

            #mcp-toggle-btn:hover {
                color: #4a6fa5;
                background-color: #f0f0f0;
            }

        /* MCP 弹窗样式 */
        #mcp-dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            width: 300px; /* 从400px改为300px，与settings宽度一致 */
            max-height: 80vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .mcp-dialog-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .mcp-dialog-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
        }

        .mcp-close-btn {
            background: none;
            border: none;
            font-size: 20px;
            color: #666;
            cursor: pointer;
        }

        .mcp-list {
            margin: 0;
            padding: 0;
        }

        .mcp-item {
            border: 1px solid #e0e5eb;
            border-radius: 6px;
            margin-bottom: 10px;
            padding: 12px;
            background-color: #f8f9fa;
        }

        .mcp-item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .mcp-item-title {
            font-weight: 500;
            color: #333;
        }

        .mcp-item-description {
            font-size: 13px;
            color: #666;
        }

        .mcp-toggle {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
        }

            .mcp-toggle input {
                opacity: 0;
                width: 0;
                height: 0;
            }

        .mcp-toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 20px;
        }

            .mcp-toggle-slider:before {
                position: absolute;
                content: "";
                height: 16px;
                width: 16px;
                left: 2px;
                bottom: 2px;
                background-color: white;
                transition: .4s;
                border-radius: 50%;
            }

        input:checked + .mcp-toggle-slider {
            background-color: #4a6fa5;
        }

            input:checked + .mcp-toggle-slider:before {
                transform: translateX(20px);
            }

        .mcp-dialog-footer {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }

        .mcp-save-btn {
            background-color: #4a6fa5;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

            .mcp-save-btn:hover {
                background-color: #3d5a7c;
            }

        #case-content.collapsed {
            display: none;
        }

        #case-toggle-arrow {
            /* 绝对定位已在HTML内联样式设置 */
        }

        #case-toggle-arrow svg {
            transition: transform 0.2s;
        }

        #case-content:not(.collapsed) ~ #case-header #case-toggle-arrow,
        #case-header.open #case-toggle-arrow {
            /* 展开时箭头向下 */
            transform: translateY(-50%) rotate(0deg);
        }

        /* ====== 校对、排版 ====== */
/*        .revisions-footer-wrapper {
            margin-right: 8px;
            margin-left: 48px;
        }*/

        .revisions-list-inner {
            display: flex;
            flex-direction: column;
            gap: 6px;
            max-height: 260px;
            overflow: auto;
            width: 100%;
        }

        .revisions-container {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-right: 12px;
            max-width: 640px;
        }

        .revisions-controls {
            display: flex;
            gap: 8px;
            align-items: center;
            margin-bottom: 6px;
        }

        .revision-item {
            display: flex;
            align-items: flex-start;
            gap: 8px;
            padding: 8px;
            background: #fafafa;
            border: 1px solid #f0f0f0;
            border-radius: 6px;
        }

            .revision-item .rev-summary {
                flex: 1;
                font-size: 12px;
                color: #333;
                white-space: pre-wrap;
            }

        .revision-checkbox {
            margin-top: 6px;
            flex: 0 0 20px;
        }

        .rev-accept-btn {
            background: #4CAF50;
            color: #fff;
            border: none;
            padding: 6px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

            .rev-accept-btn[disabled] {
                opacity: 0.6;
                cursor: default;
            }

        .revision-item.rev-accepted {
            opacity: 0.6;
            pointer-events: none;
        }

        .revisions-bottom {
            margin-top: 8px;
            display: flex;
            justify-content: flex-end;
            gap: 8px;
        }

        .revisions-action-secondary {
            background: #E9525F;
            color: #fff;
            border: none;
            padding: 6px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        /* ====== 校对、排版 end====== */
    </style>
</head>
<body>
    <div id="case-container">
        <div id="case-header" style="position:relative; background: linear-gradient(135deg, #4a6fa5 0%, #3d5a7c 100%); padding: 5px 25px; color: white; border-bottom: 1px solid rgba(255,255,255,0.1); cursor:pointer;">
            <h3 style="margin:0; font-size:1.3em; font-weight:400; letter-spacing:0.5px;">智能聊天模式说明</h3>
            <span id="case-toggle-arrow" style="position:absolute; right:18px; top:50%; transform:translateY(-50%) rotate(-90deg); display:flex; align-items:center; transition:transform 0.2s;">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
                     stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="6 9 12 15 18 9"></polyline>
                </svg>
            </span>
        </div>
        <div id="case-content" class="collapsed">
            <div id="case-info">
                <p>1.试试按#号快速提问</p>
                <p>2.会话已自动开启上下文，您可通过不断提问纠正AI的回答</p>
                <p>3.使用前请配置大模型Api，<a href="https://cloud.siliconflow.cn/i/PGhr3knx" target="_blank">点此取免费额度</a></p>
                <p>4.配置大模型提示词能够更快，更准确的得到你想要的答案</p>
                <p>5.如果没解决你的痛点，<a href="https://jsj.top/f/OZJDfa" target="_blank">点击此处提出需求</a>，下个版本见</p>
                <p>6.聊天记录存放在“当前用户/文档/OfficeAiAppData”目录下</p>
                <p>7.当前版本:<span id="version">2.6.4</span>，<a href="https://www.officeso.cn" target="_blank">每月发布新功能</a></p>
            </div>
        </div>
    </div>

    <div id="chat-container">
        <!-- message content list -->
    </div>

    <!-- message chat input bottom -->
    <div id="chat-bottom-bar">

        <!-- message input -->
        <div id="chat-input-card">
            <div id="chat-input-inner">
                <!-- 合并后的引用区域 -->
                <div id="references-wrapper" style="display:none;">
                    <span id="references-title" class="reference-section-title">引用:</span>
                    <div id="reference-chips-list" class="reference-chips-container">
                        <!-- 所有引用项（工作表内容和文件）将在此处动态添加 -->
                    </div>
                </div>

                <div id="prompt-suggestions" style="display: none;">
                    <!-- 提示词项将在此处动态添加 -->
                </div>
                <textarea id="chat-input" placeholder="请在此输入您的问题... 按Enter键直接发送，Shift+Enter换行" rows="2"></textarea>
                <div id="chat-input-actions">

                    <button id="settings-button" title="设置" onclick="settingsButton()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="12" cy="12" r="3"></circle>
                            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                        </svg>
                    </button>

                    <label class="input-option">
                        <select id="chatMode" onchange="chatModeChanged(this)">
                            <option value="chat">Chat模式</option>
                            <option value="agent">Agent模式</option>
                        </select>
                    </label>

                    <!-- 新增：附件按钮 -->
                    <button id="attach-file-button" title="添加附件" style="padding: 4px;">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path>
                        </svg>
                    </button>
                    <input type="file" id="file-input" multiple style="display: none;" accept=".xls,.xlsx,.xlsm,.xlsb,.csv,.doc,.docx,.ppt,.pptx">

                    <button id="send-button" title="发送">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width: 20px; height: 20px;">
                            <line x1="22" y1="2" x2="11" y2="13"></line>
                            <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                        </svg>
                    </button>

                    <!-- 取消正在发送的消息 -->
                    <button id="stop-button" title="取消" onclick="stopButton()">
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
                            <rect x="3" y="3" width="10" height="10" fill="white" rx="1"></rect>
                        </svg>
                    </button>

                    <!-- MCP 按钮 -->
                    <button id="mcp-toggle-btn" title="配置MCP工具">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"></path>
                        </svg>
                    </button>

                    <button id="clear-context-btn" title="清理记忆或聊天记录">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M3 6h18"></path>
                            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"></path>
                            <path d="M10 11v6"></path>
                            <path d="M14 11v6"></path>
                            <path d="M9 3V4a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2V3"></path>
                        </svg>
                    </button>

                    <!-- 新增：历史记录按钮，放在取消按钮之后 -->
                    <button id="history-toggle-btn" title="查看历史聊天记录">
                        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="12" cy="12" r="10"></circle>
                            <polyline points="12,6 12,12 16,14"></polyline>
                        </svg>
                    </button>

                </div>
            </div>
        </div>
    </div>

    <!-- MCP 配置弹窗 -->
    <div id="mcp-dialog">
        <div class="mcp-dialog-header">
            <span class="mcp-dialog-title">MCP工具配置</span>
            <button class="mcp-close-btn" id="mcp-close-btn">&times;</button>
        </div>
        <div id="mcp-list" class="mcp-list">
            <!-- MCP列表将在这里动态生成 -->
        </div>
        <div class="mcp-dialog-footer">
            <button class="mcp-save-btn" id="mcp-save-btn">保存设置</button>
        </div>
    </div>

    <!-- MCP弹窗遮罩 -->
    <div class="overlay" id="mcp-overlay"></div>

    <!-- 历史记录侧边栏 -->
    <div id="history-sidebar" class="sidebar-hidden">
        <div class="sidebar-header">
            <h3>历史聊天记录</h3>
            <button id="close-sidebar-btn" title="关闭">×</button>
        </div>
        <div class="sidebar-content">
            <div id="history-list">
                <!-- 历史记录列表将在这里动态加载 -->
            </div>
        </div>
    </div>

    <!-- 遮罩层 -->
    <div id="sidebar-overlay" class="overlay-hidden"></div>

    <!-- 添加设置对话框 -->
    <div class="overlay" id="settings-overlay"></div>
    <div class="settings-dialog" id="settings-dialog">
        <div class="settings-title">AI对话设置</div>

        <div class="setting-item checkbox-item">
            <div>
                <label class="setting-label">实时滚动对话内容</label>
                <input type="checkbox" id="settings-scroll-checked">
            </div>
            <div class="setting-tip">开启后会自动滚动到最新的对话内容</div>
        </div>

        <div class="setting-item checkbox-item">
            <div>
                <label class="setting-label">引用选中内容</label>
                <input type="checkbox" id="settings-selected-cell">
            </div>
            <div class="setting-tip">开启后可以选择并引用工作表内容</div>
        </div>

        <div class="setting-item checkbox-item">
            <div>
                <label class="setting-label">工作表变更预览</label>
                <input type="checkbox" id="settings-executecode-preview">
            </div>
            <div class="setting-tip">开启后，Agent模式下可提前预览变更点，对比差异</div>
        </div>

        <div class="setting-item">
            <label class="setting-label">话题随机性</label>
            <div class="slider-container">
                <input type="range" class="slider" id="topic-randomness" min="0.1" max="1.6" step="0.1" value="0.8">
                <span class="slider-value" id="topic-randomness-value">0.8</span>
            </div>
            <div class="setting-tip">较高的数值会使同问题每次输出的结果更随机</div>
        </div>

        <div class="setting-item">
            <label class="setting-label">上下文数量限制</label>
            <div class="slider-container">
                <input type="range" class="slider" id="context-limit" min="1" max="10" value="5">
                <span class="slider-value" id="context-limit-value">5</span>
            </div>
            <div class="setting-tip">单条回复记录对话数，每次想让ai记住历史多少条对话</div>
        </div>

        <div class="settings-buttons">
            <button class="settings-button cancel-button" id="settings-cancel" onclick="settingsCancel()">取消</button>
            <button class="settings-button save-button" id="settings-save" onclick="settingsSave()">保存</button>
        </div>
    </div>

    <!-- 2. 修改弹窗内容为三选一 -->
    <div id="clear-or-delete-actions" style="display:none; position:fixed; bottom:80px; left:50%; transform:translateX(-50%); z-index:999;">
        <div style="background:white; border-radius:8px; box-shadow:0 2px 12px rgba(0,0,0,0.12); padding:18px 18px;">
            <div style="font-size:15px; margin-bottom:16px;">选择你要进行的操作：</div>
            <button id="action-clear-context" style="background: #4a6fa5; color: white; border: none; padding: 5px 5px; border-radius: 6px; margin-right: 10px; margin-bottom: 2px;">清空聊天上下文记忆</button>
            <button id="action-delete-chat" style="background: #e9525f; color: white; border: none; padding: 5px 5px; border-radius: 6px; margin-right: 10px; margin-bottom: 2px; ">批量删除聊天记录</button>
            <button id="action-cancel" style="background:#f5f5f5;color:#333;border:none;padding:5px 10px;border-radius:6px;">我可能点错了</button>
        </div>
    </div>

    <!-- 删除聊天 -->
    <div id="delete-chat-actions" style="display:none; position:fixed; bottom:80px; left:50%; transform:translateX(-50%); z-index:999;">
        <button id="confirm-delete-chat" style="background:#e9525f;color:white;border:none;padding:6px 16px;border-radius:6px;margin-right:10px;">确定删除</button>
        <button id="cancel-delete-chat" style="background:#f5f5f5;color:#333;border:none;padding:6px 16px;border-radius:6px;">取消</button>
    </div>

    <script type="text/javascript">
        // config marked
        marked.setOptions({
            highlight: function (code, lang) {
                if (lang && hljs.getLanguage(lang)) {
                    return hljs.highlight(code, { language: lang }).value;
                }
                return hljs.highlightAuto(code).value;
            },
            breaks: true,
            gfm: true
        });

        // extends marked renderer
        const renderer = new marked.Renderer();
        const originalCodeRenderer = renderer.code;

        renderer.code = function (code, language, isEscaped) {
            const codeHtml = originalCodeRenderer.call(this, code, language, isEscaped);

            // add button
            return `
                                                                                            <div class="code-block">
                                                                                                ${codeHtml}
                                                                                                <div class="code-buttons">
                                                                                                    <button class="code-button copy-button" onclick="copyCode(this)">
                                                                                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                                                                            <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                                                                                                            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                                                                                                        </svg>
                                                                                                        复制
                                                                                                    </button>
                                                                                                    <button class="code-button edit-button" onclick="editCode(this)">
                                                                                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                                                                            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                                                                                                            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                                                                                                        </svg>
                                                                                                        编辑
                                                                                                    </button>
                                                                                                    <button class="code-button execute-button" onclick="executeCode(this)">
                                                                                                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                                                                            <polygon points="5 3 19 12 5 21 5 3"></polygon>
                                                                                                        </svg>
                                                                                                        执行
                                                                                                    </button>
                                                                                                </div>
                                                                                            </div>
                                                                                        `;
        };

        marked.use({ renderer });

        function copyCode(button) {
            const codeBlock = button.closest('.code-block');
            const codeElement = codeBlock.querySelector('code');
            const code = codeElement.textContent;

            // craete temp text area
            const textarea = document.createElement('textarea');
            textarea.value = code;
            textarea.style.position = 'fixed';
            textarea.style.opacity = '0';
            document.body.appendChild(textarea);

            try {
                textarea.select();
                textarea.setSelectionRange(0, 99999);
                document.execCommand('copy');

                const originalText = button.innerHTML;
                button.innerHTML = `
                                                                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                                                                                    <polyline points="20 6 9 17 4 12"></polyline>
                                                                                                </svg>
                                                                                                已复制
                                                                                            `;
                setTimeout(() => {
                    button.innerHTML = originalText;
                }, 2000);
            } catch (err) {
                console.error('copy failure:', err);
                alert('copy failure');
            } finally {
                // clean
                document.body.removeChild(textarea);
            }
        }

        function executeCode(button) {
            const codeBlock = button.closest('.code-block');
            const codeElement = codeBlock.querySelector('code');
            const code = codeElement.textContent;
            const language = codeElement.className.replace('language-', '');
            let preview = document.getElementById('settings-executecode-preview').checked;

            try {
                // 找到所属 chat 容器，读取 responseUuid 与 requestUuid
                const chatContainer = button.closest('.chat-container');
                let responseUuid = null;
                let requestUuid = null;
                if (chatContainer && chatContainer.id && chatContainer.id.startsWith('chat-')) {
                    responseUuid = chatContainer.id.replace('chat-', '');
                    requestUuid = chatContainer.dataset ? chatContainer.dataset.requestId : null;
                }

                const payload = {
                    type: 'executeCode',
                    code: code,
                    language: language,
                    executecodePreview: preview,
                    responseUuid: responseUuid,
                    requestUuid: requestUuid
                };

                if (window.chrome && window.chrome.webview) {
                    window.chrome.webview.postMessage(payload);
                } else if (window.vsto) {
                    // vsto 调用兼容
                    window.vsto.executeCode(code, language, preview);
                } else {
                    alert('无法执行代码：未检测到支持的通信接口');
                }

                // UI 反馈
                const originalText = button.innerHTML;
                button.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <polygon points="5 3 19 12 5 21 5 3"></polygon>
                </svg>
                已执行
            `;
                setTimeout(() => {
                    button.innerHTML = originalText;
                }, 2000);
            } catch (err) {
                alert('执行失败：' + err.message);
            }
        }

        class MarkdownStreamRenderer {
            constructor(element) {
                this.output = element instanceof HTMLElement ? element : document.getElementById(element);
                this.fullContent = '';
            }

            append(text) {
                this.fullContent += text + '';

                // use full content render
                this.output.innerHTML = marked.parse(this.fullContent);

                // code highlight
                this.output.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });

            }
        }


        // 确保所有函数都在全局作用域中定义
        window.rendererMap = {};
        window.reasoningRendererMap = {};

        // 创建聊天区域，包含发送者信息和内容区域，但不包含推理区域
        window.createChatSection = function (sender, timestamp, uuid) {

            // 创建聊天容器
            const chatContainer = document.createElement('div');
            chatContainer.className = 'chat-container';
            chatContainer.id = 'chat-' + uuid;

            // 记录 sender，以便后续判断（'Me' 或 AI）
            chatContainer.dataset.sender = sender;

            // 创建发送者信息区域
            const messageHeader = document.createElement('div');
            messageHeader.className = 'message-header';

            // 添加头像
            const avatar = document.createElement('div');
            if (sender !== 'Me') {
                avatar.innerHTML = 'AI';
                avatar.className = 'avatar-ai';
            } else {
                avatar.innerHTML = 'Me';
                avatar.className = 'avatar-me';
            }
            messageHeader.appendChild(avatar);

            // 添加发送者名称和时间戳
            const senderInfo = document.createElement('div');
            senderInfo.className = 'sender-info';

            const senderName = document.createElement('div');
            senderName.className = 'sender-name';
            senderName.textContent = sender;

            const timestampElem = document.createElement('div');
            timestampElem.className = 'timestamp';
            timestampElem.textContent = timestamp;

            senderInfo.appendChild(senderName);
            senderInfo.appendChild(timestampElem);
            messageHeader.appendChild(senderInfo);

            chatContainer.appendChild(messageHeader);

            // 创建内容区域
            const contentContainer = document.createElement('div');
            contentContainer.className = 'message-content';
            contentContainer.id = 'content-' + uuid;
            chatContainer.appendChild(contentContainer);

            // 添加footer区域（用于 token / accept-reject 按钮）
            const footerContainer = document.createElement('div');
            footerContainer.className = 'message-footer';
            footerContainer.id = 'footer-' + uuid;
            chatContainer.appendChild(footerContainer);

            // 将聊天容器添加到聊天容器
            const chatHistoryContainer = document.getElementById('chat-container');
            if (chatHistoryContainer) {
                chatHistoryContainer.appendChild(chatContainer);
            } else {
                console.error('找不到 chat-container 元素，请确保页面中存在此元素');
                document.body.appendChild(chatContainer); // 回退到添加到 body
            }

            // 创建渲染器
            window.rendererMap[uuid] = new MarkdownStreamRenderer(contentContainer.id);


            return uuid;
        };

        // 为指定的聊天区域添加推理容器
        window.createReasoningContainer = function (uuid) {
            if (!uuid) {
                console.error('UUID不能为空');
                return false;
            }

            // 检查是否已经存在推理容器
            if (document.getElementById('reasoning-' + uuid)) {
                console.warn('UUID为' + uuid + '的推理容器已存在');
                return true;
            }

            const chatContainer = document.getElementById('chat-' + uuid);
            if (!chatContainer) {
                console.error('找不到UUID为' + uuid + '的聊天容器');
                return false;
            }

            // 创建推理容器
            const reasoningContainer = document.createElement('div');
            reasoningContainer.className = 'reasoning-container';
            reasoningContainer.id = 'reasoning-' + uuid;

            // 创建推理标题栏
            const reasoningHeader = document.createElement('div');
            reasoningHeader.className = 'reasoning-header';
            reasoningHeader.innerHTML = `
                                                                                            <span class="reasoning-title">
                                                                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                                                                                                    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z"/>
                                                                                                </svg>
                                                                                                思考过程
                                                                                            </span>
                                                                                            <span class="reasoning-toggle">
                                                                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                                                                                                    <path d="M7 10l5 5 5-5z"/>
                                                                                                </svg>
                                                                                            </span>
                                                                                        `;

            // 添加点击事件以展开/折叠推理内容
            reasoningHeader.addEventListener('click', function () {
                reasoningContainer.classList.toggle('collapsed');
            });

            // 创建推理内容区域
            const reasoningContent = document.createElement('div');
            reasoningContent.className = 'reasoning-content';
            reasoningContent.id = 'reasoning-content-' + uuid;

            // 将推理标题和内容添加到推理容器
            reasoningContainer.appendChild(reasoningHeader);
            reasoningContainer.appendChild(reasoningContent);

            // 将推理容器插入到消息头部和内容之间
            const contentContainer = document.getElementById('content-' + uuid);
            chatContainer.insertBefore(reasoningContainer, contentContainer);

            // 创建推理渲染器
            window.reasoningRendererMap[uuid] = new MarkdownStreamRenderer(reasoningContent);

            return true;
        };

        // 添加用户滚动状态跟踪
        window.userScrollPosition = 0;
        window.autoScrollEnabled = true;


        // 修改 appendRenderer 函数
        window.appendRenderer = function (uuid, text) {
            if (!uuid) {
                return false;
            }

            // 检查是否存在推理容器，如果存在且未折叠，则自动折叠
            const reasoningContainer = document.getElementById('reasoning-' + uuid);
            if (reasoningContainer && !reasoningContainer.classList.contains('collapsed')) {
                reasoningContainer.classList.add('collapsed');
            }

            const renderer = window.rendererMap[uuid];
            if (renderer) {
                // 记录添加内容前的文档高度

                renderer.append(text);

                contentScroll();
                return true;
            } else {
                console.error('找不到UUID为' + uuid + '的渲染器');
                return false;
            }
        };

        // 添加推理内容的函数
        window.appendReasoning = function (uuid, text) {
            if (!uuid) {
                console.error('UUID不能为空');
                return false;
            }

            // 如果推理容器不存在，先创建它
            if (!document.getElementById('reasoning-' + uuid)) {
                if (!window.createReasoningContainer(uuid)) {
                    return false;
                }
            }

            const reasoningRenderer = window.reasoningRendererMap[uuid];
            if (reasoningRenderer) {
                // 添加内容
                reasoningRenderer.append(text);

                // 确保推理容器可见（在推理过程中）
                const reasoningContainer = document.getElementById('reasoning-' + uuid);
                if (reasoningContainer) {
                    reasoningContainer.classList.remove('collapsed');
                }
                // 获取推理内容区域并滚动到底部
                const reasoningContent = document.getElementById('reasoning-content-' + uuid);
                if (reasoningContent) {
                    reasoningContent.scrollTop = reasoningContent.scrollHeight;
                }
                contentScroll()
                return true;
            } else {
                console.error('找不到UUID为' + uuid + '的推理渲染器');
                return false;
            }
        };

        //下拉滚动条
        window.contentScroll = function () {
            if (document.getElementById("settings-scroll-checked").checked) {
                window.scrollTo(0, document.body.scrollHeight);
            }
        }

        // 完成推理过程，折叠推理区域
        window.completeReasoning = function (uuid) {
            if (!uuid) {
                console.error('UUID不能为空');
                return false;
            }

            const reasoningContainer = document.getElementById('reasoning-' + uuid);
            if (reasoningContainer) {
                // 添加一个短暂的延迟，让用户看到最终的推理结果
                setTimeout(() => {
                    reasoningContainer.classList.add('collapsed');
                }, 1000);
                return true;
            } else {
                console.error('找不到UUID为' + uuid + '的推理容器');
                return false;
            }
        };
        // 添加停止按钮点击处理函数
        function stopButton() {
            //sendMessageToServer('InnerStopBtn_#');
            sendMessageToServer({
                type: 'stopMessage'
            });
        };
        function changeSendButton() {
            // 强制切换回发送按钮
            const sendButton = document.getElementById('send-button');
            const stopButton = document.getElementById('stop-button');

            sendButton.style.setProperty('display', 'flex', 'important');
            stopButton.style.setProperty('display', 'none', 'important');
        }

        //消息接收完成的通知
        function processStreamComplete(uuid, totalTokens) {

            // 添加token展示
            const footerDiv = document.getElementById('footer-' + uuid);
            if (footerDiv) {
                footerDiv.innerHTML = `<span class="token-count">消耗token：${totalTokens}</span>`;
            }

            // 强制切换回发送按钮
            const sendButton = document.getElementById('send-button');
            const stopButton = document.getElementById('stop-button');

            sendButton.style.setProperty('display', 'flex', 'important');
            stopButton.style.setProperty('display', 'none', 'important');


            //折叠代码块区域
            // 首先获取对应uuid的内容区域
            const contentDiv = document.getElementById('content-' + uuid);
            if (contentDiv) {
                // 找到所有代码块
                const codeBlocks = contentDiv.querySelectorAll('pre code');
                codeBlocks.forEach(codeBlock => {
                    // 获取代码块的父元素
                    const preElement = codeBlock.parentElement;
                    if (preElement) {
                        // 如果父元素还没有折叠样式，添加折叠相关的样式和功能
                        if (!preElement.classList.contains('collapsible')) {
                            // 添加折叠样式类
                            preElement.classList.add('collapsible', 'collapsed');

                            // 创建展开/折叠标签
                            const toggleLabel = document.createElement('div');
                            toggleLabel.className = 'code-toggle-label';
                            toggleLabel.innerHTML = '点击展开代码';
                            toggleLabel.onclick = function (e) {
                                e.stopPropagation();
                                preElement.classList.toggle('collapsed');
                                toggleLabel.innerHTML = preElement.classList.contains('collapsed') ? '点击展开代码' : '点击折叠代码';
                            };

                            // 将标签插入到代码块前面
                            preElement.parentNode.insertBefore(toggleLabel, preElement);
                        }
                    }
                });
            }

            if (document.getElementById("chatMode").value === 'agent') {
                let executeBtns = document.getElementById("content-" + uuid).querySelector(".execute-button");
                if (executeBtns) {
                    executeBtns.click();
                }
            }

            // 新：为 AI 消息渲染 接受/拒绝 按钮（只针对非 Me 的消息）
            try {
                renderAcceptRejectButtons(uuid);
            } catch (err) {
                console.error('renderAcceptRejectButtons error:', err);
            }
        }

        // 渲染接受/拒绝按钮（仅对非 Me 的 AI 消息显示）
        function renderAcceptRejectButtons(uuid) {
            try {
                const chatDiv = document.getElementById('chat-' + uuid);
                if (!chatDiv) return;
                // 如果 sender 未设置，尝试从内容判断（保险）
                const sender = chatDiv.dataset && chatDiv.dataset.sender ? chatDiv.dataset.sender : (chatDiv.querySelector('.sender-name') ? chatDiv.querySelector('.sender-name').textContent : '');

                // 仅对 AI 消息显示按钮
                if (!sender || sender === 'Me') return;

                const footer = document.getElementById('footer-' + uuid);
                if (!footer) return;

                // 如果已经存在按钮则跳过（避免重复渲染）
                if (footer.querySelector('.accept-btn') || footer.querySelector('.reject-btn')) return;

                const btnAccept = document.createElement('button');
                btnAccept.className = 'code-button accept-btn';
                btnAccept.style.backgroundColor = '#4CAF50';
                btnAccept.style.marginRight = '8px';
                btnAccept.textContent = '接受该答案';
                btnAccept.onclick = function () { acceptAnswer(uuid); };

                const btnReject = document.createElement('button');
                btnReject.className = 'code-button reject-btn';
                btnReject.style.backgroundColor = '#E9525F';
                btnReject.textContent = '不接受，继续改进';
                btnReject.onclick = function () { rejectAnswer(uuid); };

                // 将按钮插入到 footer 左侧（token-count 保持在右侧）
                footer.insertBefore(btnReject, footer.firstChild);
                //footer.insertBefore(btnAccept, footer.firstChild);
            } catch (err) {
                console.error('renderAcceptRejectButtons error:', err);
            }
        }

        // --- 新增：用户点击“接受”后发送到后端（包含 uuid 与回答文本） ---
        function acceptAnswer(uuid) {
            try {
                const contentDiv = document.getElementById('content-' + uuid);
                const plainText = contentDiv ? (contentDiv.innerText || contentDiv.textContent || '') : '';

                // 发送到后端
                sendMessageToServer({
                    type: 'acceptAnswer',
                    uuid: uuid,
                    content: plainText
                });

                // 更新 UI：禁用按钮并显示已接受
                const footer = document.getElementById('footer-' + uuid);
                if (footer) {
                    footer.querySelectorAll('.accept-btn, .reject-btn').forEach(b => b.disabled = true);
                    const statusSpan = document.createElement('span');
                    statusSpan.className = 'token-count';
                    statusSpan.textContent = '已接受';
                    // 清除原有文本显示（可根据需求保留 token 显示）
                    footer.appendChild(statusSpan);
                }
            } catch (err) {
                console.error('acceptAnswer error:', err);
            }
        }

        // --- 新增：用户点击“拒绝/继续改进”后发送到后端（包含 uuid 与回答文本） ---
        function rejectAnswer(uuid) {
            try {
                const contentDiv = document.getElementById('content-' + uuid);
                const plainText = contentDiv ? (contentDiv.innerText || contentDiv.textContent || '') : '';

                // 弹出可选说明，用户可以留空
                let reason = '';
                try {
                    reason = prompt('请简要说明希望如何改进（可留空）：', '');
                    if (reason === null) {
                        // 用户取消 prompt，视作不进行改进请求
                        return;
                    }
                } catch (e) {
                    reason = '';
                }

                // 发送到后端，后端会把它当作新的 user 请求来发起改进
                sendMessageToServer({
                    type: 'rejectAnswer',
                    uuid: uuid,
                    content: plainText,
                    reason: reason
                });

                // 更新 UI：显示正在请求改进
                const footer = document.getElementById('footer-' + uuid);
                if (footer) {
                    footer.querySelectorAll('.accept-btn, .reject-btn').forEach(b => b.disabled = true);
                    const statusSpan = document.createElement('span');
                    statusSpan.className = 'token-count';
                    statusSpan.textContent = '已请求改进，等待新结果…';
                    footer.appendChild(statusSpan);
                }

                // 可选：高亮 reasoning 容器以提示用户我们将进行新的推理（如果存在）
                const reasoning = document.getElementById('reasoning-' + uuid);
                if (reasoning) {
                    reasoning.classList.remove('collapsed');
                }
            } catch (err) {
                console.error('rejectAnswer error:', err);
            }
        }

        function chatModeChanged(select) {
            settingsSave()
        }

        // 生成UUID
        function generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
        function toggleChatMessageReference(headerElement) {
            const container = headerElement.closest('.chat-message-references');
            if (container) {
                container.classList.toggle('collapsed');
            }
        }

        // 格式化日期时间
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 编辑代码函数
        function editCode(button) {
            const codeBlock = button.closest('.code-block');
            const codeElement = codeBlock.querySelector('code');
            const code = codeElement.textContent;
            const language = codeElement.className.replace('language-', '');

            // 创建编辑区域
            const editorContainer = document.createElement('div');
            editorContainer.className = 'editor-container';

            const textarea = document.createElement('textarea');
            textarea.className = 'code-editor';
            textarea.value = code;

            const buttonsDiv = document.createElement('div');
            buttonsDiv.className = 'editor-buttons';

            const saveButton = document.createElement('button');
            saveButton.className = 'code-button';
            saveButton.innerHTML = '保存';
            saveButton.onclick = function () {
                // 获取编辑后的代码
                const newCode = textarea.value;

                // 更新代码块
                const newCodeHtml = marked.parse('```' + language + '\n' + newCode + '\n```');

                // 替换整个代码块
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = newCodeHtml;
                const newCodeBlock = tempDiv.querySelector('.code-block');

                codeBlock.parentNode.replaceChild(newCodeBlock, codeBlock);

                // 重新应用语法高亮
                document.querySelectorAll('pre code').forEach((block) => {
                    hljs.highlightElement(block);
                });

                // 移除编辑区域
                editorContainer.remove();
            };

            const cancelButton = document.createElement('button');
            cancelButton.className = 'code-button';
            cancelButton.style.backgroundColor = '#f44336';
            cancelButton.innerHTML = '取消';
            cancelButton.onclick = function () {
                // 移除编辑区域，恢复代码块
                codeBlock.style.display = 'block';
                editorContainer.remove();
            };

            buttonsDiv.appendChild(cancelButton);
            buttonsDiv.appendChild(saveButton);

            editorContainer.appendChild(textarea);
            editorContainer.appendChild(buttonsDiv);

            // 隐藏原代码块，插入编辑区域
            codeBlock.style.display = 'none';
            codeBlock.parentNode.insertBefore(editorContainer, codeBlock);

            // 确保按钮可见
            textarea.focus();
            editorContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }

        // 添加清空聊天内容的函数
        window.clearAllChats = function () {
            // 获取聊天容器
            const chatContainer = document.getElementById('chat-container');
            if (chatContainer) {
                // 清空容器内容
                chatContainer.innerHTML = '';

                // 清空渲染器映射
                window.rendererMap = {};
                window.reasoningRendererMap = {};

                // 重置自动滚动
                window.autoScrollEnabled = true;

                console.log('已清空所有聊天内容');
                return true;
            } else {
                console.error('找不到聊天容器');
                return false;
            }
        };
        // 获取整个聊天容器的HTML
        window.getFullChatHTML = function () {
            const chatContainer = document.getElementById('chat-container');
            if (chatContainer) {
                return chatContainer.innerHTML;
            }
            return '';
        };

        // 设置聊天容器的HTML
        window.setFullChatHTML = function (html) {
            const chatContainer = document.getElementById('chat-container');
            if (chatContainer) {
                // 清空现有内容
                chatContainer.innerHTML = '';

                // 设置新内容
                chatContainer.innerHTML = html;

                // 重建渲染器映射
                window.rebuildRendererMaps();

                return true;
            }
            return false;
        };

        // 重建渲染器映射
        window.rebuildRendererMaps = function () {
            // 清空现有映射
            window.rendererMap = {};
            window.reasoningRendererMap = {};

            // 查找所有内容和推理容器
            const contentContainers = document.querySelectorAll('.message-content');
            const reasoningContainers = document.querySelectorAll('.reasoning-content');

            // 重建内容渲染器映射
            contentContainers.forEach(container => {
                const id = container.id;
                if (id && id.startsWith('content-')) {
                    const uuid = id.replace('content-', '');
                    window.rendererMap[uuid] = new MarkdownStreamRenderer(id);
                }
            });

            // 重建推理渲染器映射
            reasoningContainers.forEach(container => {
                const id = container.id;
                if (id && id.startsWith('reasoning-content-')) {
                    const uuid = id.replace('reasoning-content-', '');
                    window.reasoningRendererMap[uuid] = new MarkdownStreamRenderer(id);
                }
            });

            console.log('已重建渲染器映射');
            return true;
        };

        // 自适应textarea高度
        const chatInput = document.getElementById('chat-input');

        // 展开/折叠引用区
        function toggleReference(uuid) {
            const ref = document.getElementById('reference-' + uuid);
            if (ref) {
                ref.classList.toggle('collapsed');
            }
        }

        function sendMessageToServer(messagePayload) { // Modified to accept a payload
            if (window.chrome && window.chrome.webview) {
                window.chrome.webview.postMessage(messagePayload); // Send the whole payload
            } else if (window.vsto) {
                if (typeof window.vsto.sendMessage === 'function') {
                    if (messagePayload.type === 'sendMessage' && typeof messagePayload.value === 'object') {
                        window.vsto.sendMessage(JSON.stringify(messagePayload.value));
                    } else {
                        window.vsto.sendMessage(messagePayload); // Or adjust as per vsto.sendMessage signature
                    }
                } else if (typeof window.vsto.postMessage === 'function') { // Fallback if postMessage exists on vsto
                    window.vsto.postMessage(messagePayload);
                }
            } else {
                alert('无法执行代码：未检测到支持的通信接口');
            }
        }
        function sendChatMessage() {
            const userTypedText = chatInput.value.trim(); // 用户的原始输入
            const attachedFileObjects = window.attachedFiles; // 保持 File 对象数组
            const selectedSheetContent = window.getAllSelectedContent(); // 获取选中的工作表内容

            // 检查是否有任何内容发送
            if (!userTypedText && attachedFileObjects.length === 0 && selectedSheetContent.length === 0) return;

            // 强制切换按钮显示状态
            const sendButton = document.getElementById('send-button');
            const stopButton = document.getElementById('stop-button');

            sendButton.style.setProperty('display', 'none', 'important');
            stopButton.style.setProperty('display', 'flex', 'important');

            // 准备发送到后端的数据
            const messagePayloadValue = {
                text: userTypedText,
                filePaths: attachedFileObjects.map(file => (file && typeof file.path === 'string' && file.path) ? file.path : file.name),
                selectedContent: selectedSheetContent
            };

            sendMessageToServer({
                type: 'sendMessage',
                value: messagePayloadValue
            });

            const uuid = generateUUID();
            const now = new Date();
            const timestamp = formatDateTime(now);

            // 1. 创建基本的聊天节（头像、名称、时间戳、空的 message-content div）
            createChatSection('Me', timestamp, uuid);

            // 2. 获取刚创建的 message-content div
            const messageContentDiv = document.getElementById('content-' + uuid);
            if (!messageContentDiv) {
                console.error('Could not find message content div for ' + uuid);
                return;
            }

            // 3. 构建并设置 message-content div 的 innerHTML
            let htmlContent = '';

            // 3a. 添加用户输入的文本 (Markdown 解析)
            if (userTypedText) {
                htmlContent += marked.parse(userTypedText);
            }

            // 3b. 添加可折叠的 "引用内容"
            if (selectedSheetContent.length > 0) {
                let itemsHtml = selectedSheetContent.map(item => `<div>${item.sheetName}: ${item.address}</div>`).join('');
                htmlContent += `
                                                        <div class="chat-message-references collapsed" id="msg-ref-sel-${uuid}">
                                                            <div class="chat-message-reference-header" onclick="toggleChatMessageReference(this)">
                                                                <span class="chat-message-reference-arrow">&#9658;</span>
                                                                <span class="chat-message-reference-label">引用内容 (${selectedSheetContent.length})</span>
                                                            </div>
                                                            <div class="chat-message-reference-content">
                                                                ${itemsHtml}
                                                            </div>
                                                        </div>`;
            }

            // 3c. 添加可折叠的 "引用文件"
            if (attachedFileObjects.length > 0) {
                let displayItemsHtml = attachedFileObjects.map(file => `<div>${escapeHtml(file.name)}</div>`).join('');
                htmlContent += `
                                            <div class="chat-message-references collapsed" id="msg-ref-file-${uuid}">
                                                <div class="chat-message-reference-header" onclick="toggleChatMessageReference(this)">
                                                    <span class="chat-message-reference-arrow">&#9658;</span>
                                                    <span class="chat-message-reference-label">引用文件 (${attachedFileObjects.length})</span>
                                                </div>
                                                <div class="chat-message-reference-content">
                                                    ${displayItemsHtml}
                                                </div>
                                            </div>`;
            }

            messageContentDiv.innerHTML = htmlContent;

            // 3d. 如果用户文本中包含代码块，需要重新高亮
            messageContentDiv.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
                // 如果需要，这里也可以重新附加代码块的复制/编辑/执行按钮逻辑
                // 但由于 marked.parse 已经处理了按钮，可能不需要重复
            });

            // 4. 清空输入区域的引用和文本框
            window.selectedContentMap = {};
            window.attachedFiles = []; // 清空 File 对象数组
            renderReferences(); // 更新输入区域的引用显示

            chatInput.value = '';
            chatInput.style.height = 'auto'; // 重置输入框高度
            hidePromptSuggestions();

            // 5. 滚动到最新消息
            //contentScroll();
        }

        function escapeHtml(unsafe) {
            if (typeof unsafe !== 'string') return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
        // 发送按钮点击
        document.getElementById('send-button').onclick = sendChatMessage;


        // 回车发送，Shift+Enter换行
        chatInput.addEventListener('keydown', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendChatMessage();
            }
        });


        window.selectedContentMap = {}; // { sheetName: Set(address1, address2, ...) }

        // 添加选中内容（支持Ctrl多选，否则单选）
        window.addSelectedContentItem = function (sheetName, address, ctrlKey) {
            if (!address || address.trim() === '') {
                return;
            }
            const newItemId = generateUUID();
            const newItem = { id: newItemId, address: address.trim() };

            if (!ctrlKey) {
                //window.selectedContentMap = {};
                window.selectedContentMap[sheetName] = newItem;
            } else {
                window.selectedContentMap[sheetName] = newItem;
            }
            renderReferences(); // <--- 更新调用
        };

        // 清除指定 sheetName 的选中内容
        window.clearSelectedContentBySheetName = function (sheetName) {
            if (window.selectedContentMap && window.selectedContentMap.hasOwnProperty(sheetName)) {
                // 删除该 sheetName 对应的引用内容
                delete window.selectedContentMap[sheetName];
                // 更新页面上的引用显示
                renderReferences();
            }
        };

        // 移除单个内容
        // 修改后：通过itemId移除
        window.removeSelectedContentItem = function (itemIdToRemove) {
            for (const sheetName in window.selectedContentMap) {
                if (window.selectedContentMap.hasOwnProperty(sheetName)) {
                    if (window.selectedContentMap[sheetName] && window.selectedContentMap[sheetName].id === itemIdToRemove) {
                        delete window.selectedContentMap[sheetName];
                        break;
                    }
                }
            }
            renderReferences(); // <--- 更新调用
        };


        // 获取所有选中内容
        // 修改后：适配新的selectedContentMap结构
        window.getAllSelectedContent = function () {
            const arr = [];
            for (const sheetName in window.selectedContentMap) {
                if (window.selectedContentMap.hasOwnProperty(sheetName)) {
                    const selectedItem = window.selectedContentMap[sheetName];
                    if (selectedItem) {
                        // 可以选择是否也返回id，取决于其他地方是否需要
                        arr.push({ sheetName: sheetName, address: selectedItem.address, id: selectedItem.id });
                    }
                }
            }
            return arr;
        };

        // 自适应textarea高度 和 提示词建议逻辑
        const promptSuggestionsDiv = document.getElementById('prompt-suggestions');
        const attachFileButton = document.getElementById('attach-file-button');
        const fileInput = document.getElementById('file-input');

        // 获取新的统一引用区域的元素
        const referencesWrapper = document.getElementById('references-wrapper');
        const referencesTitle = document.getElementById('references-title'); // 应该已在HTML中设置为 "引用:"
        const referenceChipsList = document.getElementById('reference-chips-list');


        window.attachedFiles = []; // Array to store selected File objects
        window.selectedContentMap = {};

        // 预定义的提示词列表
        const predefinedPrompts = [
            "帮我把A列加B列的值写入C列",
            "帮我把Sheet1和Sheet2的表格按名字合并",
            "帮我把Sheet1的数据，按照中文名称拆分成多个xlsx文件",
            "给我将我选中的Word内容格式调整一下",
            "给我生成一个3页的周报PPT文件",
            "什么？没有你想要的，点击此处维护吧",
        ];

        function showPromptSuggestions() {
            promptSuggestionsDiv.innerHTML = ''; // 清空旧建议
            predefinedPrompts.forEach(promptText => {
                const item = document.createElement('div');
                item.className = 'prompt-suggestion-item';
                item.textContent = promptText;
                item.onclick = function () {
                    chatInput.value = promptText;
                    hidePromptSuggestions();
                    chatInput.focus();
                    // 触发input事件以调整高度
                    const event = new Event('input', { bubbles: true, cancelable: true });
                    chatInput.dispatchEvent(event);
                };
                promptSuggestionsDiv.appendChild(item);
            });
            promptSuggestionsDiv.style.display = 'block';
        }

        function hidePromptSuggestions() {
            promptSuggestionsDiv.style.display = 'none';
        }


        // --- 新的统一渲染函数 ---
        function renderReferences() {
            if (!referencesWrapper || !referenceChipsList || !referencesTitle) {
                console.error("Reference display elements not found!");
                return;
            }

            referenceChipsList.innerHTML = ''; // 清空所有现有的chips
            let hasAnyReferences = false;

            // 1. 渲染选中的工作表内容
            for (const sheetName in window.selectedContentMap) {
                if (window.selectedContentMap.hasOwnProperty(sheetName)) {
                    const selectedItem = window.selectedContentMap[sheetName];
                    if (!selectedItem) continue;
                    hasAnyReferences = true;

                    const itemChip = document.createElement('div');
                    itemChip.className = 'reference-chip';
                    itemChip.title = `${sheetName} [${selectedItem.address}]`;

                    const chipContentWrapper = document.createElement('div');
                    chipContentWrapper.className = 'reference-chip-content-wrapper';

                    const itemNameSpan = document.createElement('span');
                    itemNameSpan.className = 'reference-chip-name';
                    itemNameSpan.textContent = `${sheetName}: ${selectedItem.address}`;
                    chipContentWrapper.appendChild(itemNameSpan);

                    const removeBtn = document.createElement('button');
                    removeBtn.className = 'reference-chip-remove';
                    removeBtn.title = '移除此引用';
                    removeBtn.innerHTML = `<svg viewBox="0 0 20 20"><line x1="5" y1="5" x2="15" y2="15" stroke="currentColor" stroke-width="2"/><line x1="15" y1="5" x2="5" y2="15" stroke="currentColor" stroke-width="2"/></svg>`;
                    removeBtn.onclick = function () {
                        removeSelectedContentItem(selectedItem.id); // 调用已有的移除函数
                    };
                    chipContentWrapper.appendChild(removeBtn);
                    itemChip.appendChild(chipContentWrapper);
                    referenceChipsList.appendChild(itemChip);
                }
            }

            // 2. 渲染附加的文件
            window.attachedFiles.forEach((file, index) => {
                hasAnyReferences = true;
                const itemChip = document.createElement('div');
                itemChip.className = 'reference-chip';
                itemChip.title = file.name;

                const chipContentWrapper = document.createElement('div');
                chipContentWrapper.className = 'reference-chip-content-wrapper';

                const fileNameSpan = document.createElement('span');
                fileNameSpan.className = 'reference-chip-name';
                fileNameSpan.textContent = file.name;
                chipContentWrapper.appendChild(fileNameSpan);

                const removeBtn = document.createElement('button');
                removeBtn.className = 'reference-chip-remove';
                removeBtn.title = '移除此文件';
                removeBtn.innerHTML = `<svg viewBox="0 0 20 20"><line x1="5" y1="5" x2="15" y2="15" stroke="currentColor" stroke-width="2"/><line x1="15" y1="5" x2="5" y2="15" stroke="currentColor" stroke-width="2"/></svg>`;
                removeBtn.onclick = function () {
                    window.attachedFiles.splice(index, 1);
                    renderReferences(); // 重新渲染整个引用区域
                };
                chipContentWrapper.appendChild(removeBtn);
                itemChip.appendChild(chipContentWrapper);
                referenceChipsList.appendChild(itemChip);
            });

            // 3. 控制整个引用区域的显示/隐藏
            if (hasAnyReferences) {
                referencesWrapper.style.display = 'block'; // 或者 'flex' 如果 #references-wrapper 本身是flex容器
            } else {
                referencesWrapper.style.display = 'none';
            }

        }

        // --- Attachment Logic ---
        attachFileButton.addEventListener('click', () => {
            fileInput.value = ''; // Clear previous selection from file input
            fileInput.click();
        });

        fileInput.addEventListener('change', function (event) {
            const files = event.target.files;
            if (!files) return;
            const allowedExtensions = /(\.xls|\.xlsx|\.xlsm|\.xlsb|\.csv|\.doc|\.docx|\.ppt|\.pptx)$/i;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (!allowedExtensions.exec(file.name)) {
                    alert(`文件类型不支持: ${file.name}`);
                    continue;
                }
                const isDuplicate = window.attachedFiles.some(
                    existingFile => existingFile.name === file.name && existingFile.size === file.size
                );
                if (isDuplicate) {
                    console.log(`文件已添加: ${file.name}`);
                    continue;
                }
                window.attachedFiles.push(file);
            }
            renderReferences(); // <--- 更新调用
            fileInput.value = '';
        });

        // --- End Attachment Logic ---


        chatInput.addEventListener('input', function () {
            // 自适应高度
            this.style.height = 'auto';
            this.style.height = (this.scrollHeight) + 'px';

            // 提示词逻辑
            const value = this.value;
            if (value === '#') {
                showPromptSuggestions();
            } else if (!value.startsWith('#') || value.length > 1) {
                hidePromptSuggestions();
            }
        });

        // 如果用户点击textarea外部，也隐藏提示词
        document.addEventListener('click', function (event) {
            if (!chatInput.contains(event.target) && !promptSuggestionsDiv.contains(event.target) && !attachFileButton.contains(event.target)) {
                if (!event.target.closest('.reference-chip-remove')) { // Don't hide if clicking remove on a chip
                    hidePromptSuggestions();
                }
            }
        });

        function settingsButton() {
            // 显示遮罩和对话框
            document.getElementById('settings-overlay').style.display = 'block';
            document.getElementById('settings-dialog').style.display = 'block';
        }

        function settingsCancel() {
            document.getElementById('settings-overlay').style.display = 'none';
            document.getElementById('settings-dialog').style.display = 'none';
        }

        function settingsSave() {
            let topicRandomness = document.getElementById('topic-randomness').value
            let contextLimit = document.getElementById('context-limit').value
            let settingsScroll = document.getElementById('settings-scroll-checked').checked
            let selectedCell = document.getElementById('settings-selected-cell').checked
            let executeCodePreview = document.getElementById('settings-executecode-preview').checked
            let chatMode = document.getElementById("chatMode").value

            // 保存随机性和上下文限制的设置
            if (window.chrome && window.chrome.webview) {
                // ues WebView2
                window.chrome.webview.postMessage({
                    type: 'saveSettings',
                    topicRandomness: topicRandomness,
                    contextLimit: contextLimit,
                    selectedCell: selectedCell,
                    settingsScroll: settingsScroll,
                    chatMode: chatMode,
                    executeCodePreview: executeCodePreview,
                });
            } else if (window.vsto) {
                // user inject vsto object
                window.vsto.saveSettings({
                    topicRandomness: topicRandomness,
                    contextLimit: contextLimit,
                    selectedCell: selectedCell,
                    settingsScroll: settingsScroll,
                    chatMode: chatMode,
                    executeCodePreview: executeCodePreview,
                });
            } else {
                alert('无法执行代码：未检测到支持的通信接口');
            }

            // 关闭对话框
            document.getElementById('settings-overlay').style.display = 'none';
            document.getElementById('settings-dialog').style.display = 'none';
        }


        // 滑块值实时更新
        document.getElementById('topic-randomness').oninput = function () {
            document.getElementById('topic-randomness-value').textContent =
                Number(this.value).toFixed(1);
        };

        document.getElementById('context-limit').oninput = function () {
            document.getElementById('context-limit-value').textContent = this.value;
        };

        // 点击遮罩关闭对话框
        document.getElementById('settings-overlay').onclick = function () {
            document.getElementById('settings-overlay').style.display = 'none';
            document.getElementById('settings-dialog').style.display = 'none';
        };


        // 历史记录功能
        window.historyManager = {
            isOpen: false,

            // 初始化历史记录功能
            init: function () {
                const toggleBtn = document.getElementById('history-toggle-btn');
                const sidebar = document.getElementById('history-sidebar');
                const overlay = document.getElementById('sidebar-overlay');
                const closeBtn = document.getElementById('close-sidebar-btn');

                // 绑定事件
                toggleBtn.addEventListener('click', () => this.toggleSidebar());
                closeBtn.addEventListener('click', () => this.closeSidebar());
                overlay.addEventListener('click', () => this.closeSidebar());

                // 键盘事件
                document.addEventListener('keydown', (e) => {
                    if (e.key === 'Escape' && this.isOpen) {
                        this.closeSidebar();
                    }
                });
            },

            // 切换侧边栏显示/隐藏
            toggleSidebar: function () {
                if (this.isOpen) {
                    this.closeSidebar();
                } else {
                    this.openSidebar();
                }
            },

            // 打开侧边栏
            openSidebar: function () {
                const sidebar = document.getElementById('history-sidebar');
                const overlay = document.getElementById('sidebar-overlay');

                sidebar.classList.remove('sidebar-hidden');
                sidebar.classList.add('sidebar-visible');
                overlay.classList.remove('overlay-hidden');
                overlay.classList.add('overlay-visible');

                this.isOpen = true;

                // 加载历史记录
                this.loadHistoryFiles();
            },

            // 关闭侧边栏
            closeSidebar: function () {
                const sidebar = document.getElementById('history-sidebar');
                const overlay = document.getElementById('sidebar-overlay');

                sidebar.classList.remove('sidebar-visible');
                sidebar.classList.add('sidebar-hidden');
                overlay.classList.remove('overlay-visible');
                overlay.classList.add('overlay-hidden');

                this.isOpen = false;
            },

            // 加载历史记录文件列表
            loadHistoryFiles: function () {
                const historyList = document.getElementById('history-list');

                // 显示加载状态
                historyList.innerHTML = '<div class="loading-state">正在加载历史记录...</div>';

                // 发送消息到VB后端请求历史文件列表
                this.sendMessageToVB({
                    type: 'getHistoryFiles'
                });
            },

            // 接收从VB传来的历史文件列表
            displayHistoryFiles: function (files) {
                const historyList = document.getElementById('history-list');

                if (!files || files.length === 0) {
                    historyList.innerHTML = `
                                                <div class="empty-state">
                                                    <div class="empty-state-icon">📄</div>
                                                    <div class="empty-state-text">您还没有任何历史记录</div>
                                                </div>
                                            `;
                    return;
                }

                // 按文件名排序（最新的在前）
                files.sort((a, b) => b.fileName.localeCompare(a.fileName));

                // 生成文件列表HTML
                const itemsHtml = files.map(file => `
                                            <div class="history-item" onclick="historyManager.openHistoryFile('${file.fullPath.replace(/\\/g, '\\\\')}')">
                                                <div class="history-item-title">${this.formatFileName(file.fileName)}</div>
                                                <div class="history-item-date">${this.formatFileDate(file.fileName)}</div>
                                                <div class="history-item-size">${this.formatFileSize(file.size)}</div>
                                            </div>
                                        `).join('');

                historyList.innerHTML = itemsHtml;
            },

            // 格式化文件名显示
            formatFileName: function (fileName) {
                // 新格式: saved_chat_yyyyMMdd_HHmmss_中文内容.html 或 saved_chat_yyyyMMdd_HHmmss.html
                const match = fileName.match(/saved_chat_\d{8}_\d{6}_(.+)\.html/);
                if (match && match[1]) {
                    // 如果有中文内容部分，返回中文内容
                    return match[1];
                } else {
                    // 如果没有中文内容，按照原逻辑：移除 saved_chat_ 前缀和 .html 后缀
                    return fileName.replace('saved_chat_', '').replace('.html', '');
                }
            },

            // 格式化文件日期
            formatFileDate: function (fileName) {
                // 从文件名中提取日期时间信息
                // 新格式: saved_chat_yyyyMMdd_HHmmss_中文内容.html 或 saved_chat_yyyyMMdd_HHmmss.html
                const match = fileName.match(/saved_chat_(\d{8})_(\d{6})(?:_.*)?\.html/);
                if (match) {
                    const dateStr = match[1]; // yyyyMMdd
                    const timeStr = match[2]; // HHmmss

                    const year = dateStr.substring(0, 4);
                    const month = dateStr.substring(4, 6);
                    const day = dateStr.substring(6, 8);
                    const hour = timeStr.substring(0, 2);
                    const minute = timeStr.substring(2, 4);
                    const second = timeStr.substring(4, 6);

                    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                }
                return '未知时间';
            },


            // 格式化文件大小
            formatFileSize: function (bytes) {
                if (bytes === 0) return '0 B';
                const k = 1024;
                const sizes = ['B', 'KB', 'MB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
            },

            // 打开历史文件
            openHistoryFile: function (filePath) {
                // 发送消息到VB后端打开文件
                this.sendMessageToVB({
                    type: 'openHistoryFile',
                    filePath: filePath
                });

                // 关闭侧边栏
                this.closeSidebar();
            },

            // 发送消息到VB后端
            sendMessageToVB: function (message) {
                try {
                    if (window.chrome && window.chrome.webview) {
                        window.chrome.webview.postMessage(message);
                    } else if (window.vsto) {
                        if (typeof window.vsto.sendMessage === 'function') {
                            window.vsto.sendMessage(JSON.stringify(message));
                        } else if (typeof window.vsto.postMessage === 'function') {
                            window.vsto.postMessage(message);
                        }
                    } else {
                        console.error('无法与后端通信');
                    }
                } catch (error) {
                    console.error('发送消息到VB后端失败:', error);
                }
            }
        };

        // 页面加载完成后初始化历史记录功能
        document.addEventListener('DOMContentLoaded', function () {

            // 初始化MCP按钮事件
            document.getElementById('mcp-toggle-btn').addEventListener('click', toggleMcpDialog);
            document.getElementById('mcp-close-btn').addEventListener('click', closeMcpDialog);
            document.getElementById('mcp-overlay').addEventListener('click', closeMcpDialog);
            document.getElementById('mcp-save-btn').addEventListener('click', saveMcpSettings);

            historyManager.init();
        });

        // 提供全局函数供VB后端调用
        window.setHistoryFilesList = function (files) {
            historyManager.displayHistoryFiles(files);
        };

        // MCP功能相关变量
        let mcpConnections = []; // 存储MCP连接列表
        let enabledMcpList = []; // 存储已启用的MCP列表
        let mcpSupported = false; // 模型是否支持MCP

        // 每5秒执行一次，检查当前模型是否支持MCP
        setInterval(function () {
            console.log('检测')
            requestMcpConnections();
        }, 3000);

        // 显示/隐藏MCP弹窗
        function toggleMcpDialog() {
            //先校验下当前模型是否是否支持mcp
            requestMcpConnections();
            document.getElementById('mcp-dialog').style.display = 'block';
            document.getElementById('mcp-overlay').style.display = 'block';
        }

        // 关闭MCP弹窗
        function closeMcpDialog() {
            document.getElementById('mcp-dialog').style.display = 'none';
            document.getElementById('mcp-overlay').style.display = 'none';
        }

        // 向后端请求MCP连接列表
        function requestMcpConnections() {
            sendMessageToServer({
                type: 'getMcpConnections'
            });
        }

        // 渲染MCP连接列表
        // 修改MCP连接显示逻辑，适应新属性
        function renderMcpConnections(connections, enabledList, supported) {
            mcpSupported = supported;

            // 显示或隐藏MCP按钮
            const mcpButton = document.getElementById('mcp-toggle-btn');
            mcpButton.style.display = supported ? 'flex' : 'none';


            // 获取MCP连接列表容器
            const mcpList = document.getElementById('mcp-list');
            if (!mcpList) return;

            // 清空现有内容
            mcpList.innerHTML = '';

            // 如果当前模型不支持MCP，显示警告
            if (!mcpSupported) {
                mcpList.innerHTML = '<div class="mcp-warning">当前选择的模型不支持MCP功能。</div>';
                return;
            }

            // 如果没有可用连接，显示提示
            if (!connections || connections.length === 0) {
                mcpList.innerHTML = '<div class="mcp-warning">没有可用的MCP连接。请先配置MCP连接。</div>';
                return;
            }

            // 为每个连接创建项
            connections.forEach(connection => {
                const item = document.createElement('div');
                item.className = 'mcp-item';

                // 创建项头部（标题和开关）
                const header = document.createElement('div');
                header.className = 'mcp-item-header';

                // 标题
                const title = document.createElement('div');
                title.className = 'mcp-item-title';
                title.textContent = connection.name;
                header.appendChild(title);

                // 开关
                const toggleLabel = document.createElement('label');
                toggleLabel.className = 'mcp-toggle';

                const toggleInput = document.createElement('input');
                toggleInput.type = 'checkbox';
                toggleInput.checked = enabledList && enabledList.includes(connection.name);
                toggleInput.setAttribute('data-mcp-name', connection.name);

                const toggleSlider = document.createElement('span');
                toggleSlider.className = 'mcp-toggle-slider';

                toggleLabel.appendChild(toggleInput);
                toggleLabel.appendChild(toggleSlider);
                header.appendChild(toggleLabel);

                // 添加描述（如果有）
                if (connection.description) {
                    const desc = document.createElement('div');
                    desc.className = 'mcp-item-description';
                    desc.textContent = connection.description;
                    item.appendChild(desc);
                }

                // 添加连接类型信息
                const typeInfo = document.createElement('div');
                typeInfo.className = 'mcp-item-description';
                // 根据是否有command字段判断类型
                const connectionType = connection.command ? "Stdio" : "HTTP";
                const connectionUrl = connection.baseUrl || (connection.command ? `${connection.command} ${connection.args.join(' ')}` : "未知URL");
                typeInfo.textContent = `${connectionType}: ${connectionUrl}`;

                // 组装项
                item.appendChild(header);
                if (connection.description) {
                    const desc = document.createElement('div');
                    desc.className = 'mcp-item-description';
                    desc.textContent = connection.description;
                    item.appendChild(desc);
                }
                item.appendChild(typeInfo);

                // 添加到列表
                mcpList.appendChild(item);
            });
        }

        // 保存MCP设置
        function saveMcpSettings() {
            const enabledMcps = [];

            // 获取所有已启用的MCP
            document.querySelectorAll('#mcp-list input[type="checkbox"]:checked').forEach(checkbox => {
                enabledMcps.push(checkbox.getAttribute('data-mcp-name'));
            });

            // 保存设置
            sendMessageToServer({
                type: 'saveMcpSettings',
                enabledList: enabledMcps
            });

            // 更新本地存储的启用列表
            enabledMcpList = enabledMcps;

            // 关闭弹窗
            closeMcpDialog();
        }

        // 设置模型是否支持MCP
        // 修改setMcpSupport方法中的映射代码
        function setMcpSupport(supported, connections, enabledList) {
            mcpSupported = supported;

            // 显示或隐藏MCP按钮
            const mcpButton = document.getElementById('mcp-toggle-btn');
            mcpButton.style.display = supported ? 'flex' : 'none';

            // 处理属性名称不匹配问题
            if (connections) {
                // 将后端属性映射到前端需要的格式
                mcpConnections = connections.map(conn => ({
                    name: conn.name,
                    description: conn.description || "",
                    // 根据command判断连接类型
                    connectionType: conn.command ? "Stdio" : "HTTP",
                    // 使用isActive替代enabled
                    isActive: conn.isActive,
                    // baseUrl可能为null
                    baseUrl: conn.baseUrl || "",
                    command: conn.command,
                    // 映射参数和环境变量
                    args: conn.args || [],
                    env: conn.env || {}
                }));

                // 立即渲染连接列表
                renderMcpConnections(mcpConnections, enabledList, supported);
            }

            // 如果有启用列表，更新缓存
            if (enabledList) {
                enabledMcpList = enabledList;
            }
        }

        //清空上下文和记录的弹窗
        document.getElementById('clear-context-btn').addEventListener('click', function () {
            document.getElementById('clear-or-delete-actions').style.display = 'block';
        });

        // 清空上下文记忆 begin
        document.getElementById('action-clear-context').addEventListener('click', function () {
            document.getElementById('clear-or-delete-actions').style.display = 'none';
            // 清空上下文逻辑
            if (window.chrome && window.chrome.webview) {
                window.chrome.webview.postMessage({ type: 'clearContext' });
            } else if (window.vsto && typeof window.vsto.postMessage === 'function') {
                window.vsto.postMessage({ type: 'clearContext' });
            } else {
                alert('无法清空上下文：未检测到支持的通信接口');
            }
        });
        // 清空上下文记忆 begin

        // 删除聊天记录功能 begin
        document.getElementById('action-delete-chat').addEventListener('click', function () {
            document.getElementById('clear-or-delete-actions').style.display = 'none';
            // 批量删除聊天记录逻辑
            showBatchDeleteChat();
        });

        //取消清理动作
        document.getElementById('action-cancel').addEventListener('click', function () {
            document.getElementById('clear-or-delete-actions').style.display = 'none';
        });



        // 5. 批量删除聊天记录逻辑封装为函数
        function showBatchDeleteChat() {
            // 显示操作按钮
            if (!document.getElementById('delete-chat-actions')) {
                // 如果原弹窗被删除，需要重新创建
                const actionsDiv = document.createElement('div');
                actionsDiv.id = 'delete-chat-actions';
                actionsDiv.style = 'display:block; position:fixed; bottom:80px; left:50%; transform:translateX(-50%); z-index:999;';
                actionsDiv.innerHTML = `
                <button id="confirm-delete-chat" style="background:#e9525f;color:white;border:none;padding:6px 16px;border-radius:6px;margin-right:10px;">确定删除</button>
                <button id="cancel-delete-chat" style="background:#f5f5f5;color:#333;border:none;padding:6px 16px;border-radius:6px;">取消</button>
            `;
                document.body.appendChild(actionsDiv);
            } else {
                document.getElementById('delete-chat-actions').style.display = 'block';
            }
            // 插入checkbox
            document.querySelectorAll('#chat-container .chat-container').forEach(function (chatDiv) {
                if (!chatDiv.querySelector('.chat-select-checkbox')) {
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.className = 'chat-select-checkbox';
                    checkbox.style.marginRight = '8px';
                    chatDiv.insertBefore(checkbox, chatDiv.firstChild);
                }
            });

            // 绑定事件（确保只绑定一次）
            if (!window._deleteChatEventsBound) {
                document.getElementById('cancel-delete-chat').addEventListener('click', function () {
                    document.getElementById('delete-chat-actions').style.display = 'none';
                    document.querySelectorAll('#chat-container .chat-container .chat-select-checkbox').forEach(function (cb) {
                        cb.parentNode.removeChild(cb);
                    });
                });
                document.getElementById('confirm-delete-chat').addEventListener('click', function () {
                    document.querySelectorAll('#chat-container .chat-container').forEach(function (chatDiv) {
                        const cb = chatDiv.querySelector('.chat-select-checkbox');
                        if (cb && cb.checked) {
                            chatDiv.parentNode.removeChild(chatDiv);
                        }
                    });
                    document.getElementById('delete-chat-actions').style.display = 'none';
                    document.querySelectorAll('#chat-container .chat-container .chat-select-checkbox').forEach(function (cb) {
                        cb.parentNode.removeChild(cb);
                    });
                });
                window._deleteChatEventsBound = true;
            }
        }
        // 删除聊天记录功能 end


        // 折叠/展开 case-content
        document.getElementById('case-header').addEventListener('click', function () {
            var content = document.getElementById('case-content');
            var arrow = document.getElementById('case-toggle-arrow').querySelector('svg');
            if (content.classList.contains('collapsed')) {
                content.classList.remove('collapsed');
                arrow.style.transform = 'rotate(0deg)';
            } else {
                content.classList.add('collapsed');
                arrow.style.transform = 'rotate(-90deg)';
            }
        });

        // 新增：展示对比预览并支持操作
        function markdownToPlain(md) {
            try {
                const html = marked.parse(md || "");
                const tmp = document.createElement('div');
                tmp.innerHTML = html;
                return tmp.innerText || tmp.textContent || "";
            } catch (err) {
                console.error('markdownToPlain error', err);
                return md;
            }
        }


        // 前端收到后端 markRevisionHandled 调用时更新 UI（简单灰显）
        function markRevisionHandled(responseUuid, globalIndex, status) {
            try {
                const container = document.getElementById('revisions-' + responseUuid);
                if (!container) return;
                const item = Array.from(container.querySelectorAll('div')).find(d => d.innerText && d.innerText.startsWith('#' + globalIndex + ' '));
                if (item) {
                    item.style.opacity = '0.5';
                    const badge = document.createElement('span');
                    badge.className = 'token-count';
                    badge.style.marginLeft = '8px';
                    badge.textContent = status === 'accepted' ? '已接受' : '已拒绝';
                    item.appendChild(badge);
                    // 禁用按钮
                    item.querySelectorAll('button').forEach(b => b.disabled = true);
                }
            } catch (err) {
                console.error('markRevisionHandled error', err);
            }
        }
    </script>
    <script>
        (function () {
            if (!window._oa) window._oa = {};
            window._oa._comparisonCache = window._oa._comparisonCache || {};

            function stripHtml(html) {
                try {
                    const tmp = document.createElement('div');
                    tmp.innerHTML = html || '';
                    return (tmp.textContent || tmp.innerText || '').trim();
                } catch (e) {
                    return html || '';
                }
            }

            //排版预览
            //排版预览（已修改：支持每项前复选框并在 acceptAll 时跳过已执行项）
            window.showComparison = function (uuid, originalText, aiPreviewOrPlan) {
                console.log(aiPreviewOrPlan)
                try {
                    const container = document.getElementById('content-' + uuid);
                    if (!container) return;

                    const footer = document.getElementById('footer-' + uuid);
                    if (footer) {
                        try {
                            const oldReject = footer.querySelector('.reject-btn');
                            if (oldReject) oldReject.style.display = 'none';
                            const tokenCount = footer.querySelector('.token-count');
                            if (tokenCount) tokenCount.style.display = 'none';
                            const codeButtons = footer.querySelector('.code-buttons');
                            if (codeButtons) codeButtons.style.display = 'none';
                        } catch (e) { }
                    }

                    console.log(1)
                    let raw = aiPreviewOrPlan;
                    if (typeof raw === 'string') {
                        raw = raw.trim();
                        const fenceMatch = raw.match(/^\s*```([^\n]*)\n([\s\S]*?)\n```\s*$/);
                        if (fenceMatch && fenceMatch.length >= 3) {
                            raw = fenceMatch[2];
                        } else {
                            if (raw.startsWith('```')) {
                                raw = raw.replace(/^\s*```[^\n]*\n?/, '');
                                raw = raw.replace(/\n?```\s*$/, '');
                            }
                        }
                    }

                    console.log(2)
                    let planObj = null;
                    try {
                        if (typeof raw === 'string' && raw.length > 0) {
                            planObj = JSON.parse(raw);
                        } else if (typeof raw === 'object' && raw !== null) {
                            planObj = raw;
                        }
                    } catch (e) {
                        planObj = null;
                    }

                    const previewHtmlMap = planObj && planObj.previewHtmlMap ? planObj.previewHtmlMap : null;
                    const documentPlan = planObj && Array.isArray(planObj.documentPlan) ? planObj.documentPlan : null;

                    if (!previewHtmlMap || Object.keys(previewHtmlMap).length === 0) {
                        const wrapEmpty = document.createElement('div');
                        wrapEmpty.id = 'compare-' + uuid;
                        wrapEmpty.className = 'reference-container';
                        wrapEmpty.style.padding = '12px';
                        wrapEmpty.style.marginTop = '12px';
                        wrapEmpty.style.background = '#f6f8fa';
                        wrapEmpty.innerHTML = '<div style="color:#666;padding:8px;">大模型返回格式有问题，无法预览排版，请重试。</div>';
                        container.appendChild(wrapEmpty);
                        return;
                    }

                    function renderPreviewFragment(text) {
                        if (text === null || text === undefined) return '';
                        const rawText = String(text);
                        const looksLikeHtml = /<\/?[a-z][\s\S]*>/i.test(rawText);
                        if (looksLikeHtml) return rawText;
                        const esc = rawText.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                        return esc.replace(/\r?\n/g, '<br>');
                    }

                    let orderedBlockIds = [];
                    if (documentPlan && documentPlan.length > 0) {
                        documentPlan.forEach(item => {
                            const id = item.blockId || item.id;
                            if (id && previewHtmlMap[id] && !orderedBlockIds.includes(id)) orderedBlockIds.push(id);
                        });
                        Object.keys(previewHtmlMap).forEach(k => { if (!orderedBlockIds.includes(k)) orderedBlockIds.push(k); });
                    } else {
                        orderedBlockIds = Object.keys(previewHtmlMap);
                    }

                    // 持久化已执行集合（跨多次 showComparison 保留）
                    window._oa = window._oa || {};
                    window._oa._comparisonCache = window._oa._comparisonCache || {};
                    const cache = window._oa._comparisonCache[uuid] = window._oa._comparisonCache[uuid] || {};
                    cache.executedSet = cache.executedSet || new Set();
                    const executedSet = cache.executedSet;

                    // 在展示时，从 orderedBlockIds 中移除已执行的（避免 acceptAll 重复执行）
                    orderedBlockIds = orderedBlockIds.filter(id => !executedSet.has(id));

                    const wrap = document.createElement('div');
                    wrap.id = 'compare-' + uuid;
                    wrap.className = 'reference-container';
                    wrap.style.padding = '12px';
                    wrap.style.marginTop = '12px';
                    wrap.style.background = '#f6f8fa';
                    wrap.style.display = 'flex';
                    wrap.style.flexDirection = 'column';
                    wrap.style.gap = '10px';

                    // 预先创建 listWrap，方便上层按钮访问
                    const listWrap = document.createElement('div');
                    listWrap.style.display = 'flex';
                    listWrap.style.flexDirection = 'column';
                    listWrap.style.gap = '8px';

                    const header = document.createElement('div');
                    header.style.display = 'flex';
                    header.style.justifyContent = 'space-between';
                    header.style.alignItems = 'center';

                    const title = document.createElement('div');
                    title.style.fontWeight = '600';
                    title.textContent = '模型渲染预览';
                    header.appendChild(title);

                    // ops 顺序： 接受全部 | 接受选中（同一行）
                    const ops = document.createElement('div');
                    ops.style.display = 'flex';
                    ops.style.gap = '8px';
                    ops.style.alignItems = 'center';

                    const acceptAllBtn = document.createElement('button');
                    acceptAllBtn.className = 'code-button';
                    acceptAllBtn.style.backgroundColor = '#4CAF50';
                    acceptAllBtn.textContent = '接受全部变更';
                    acceptAllBtn.onclick = function () {
                        const pending = orderedBlockIds.filter(bid => !executedSet.has(bid));
                        if (pending.length === 0) {
                            acceptAllBtn.disabled = true;
                            acceptAllBtn.textContent = '已无可执行项';
                            return;
                        }
                        pending.forEach(bid => {
                            let planItem = null;
                            if (documentPlan) planItem = documentPlan.find(p => (p.blockId || p.id) === bid);
                            if (!planItem) planItem = { blockId: bid, action: 'insert_html', attributes: { previewHtml: previewHtmlMap[bid] } };
                            sendMessageToServer({ type: 'applyDocumentPlanItem', uuid: uuid, planItem: planItem });
                            executedSet.add(bid);
                            const cb = listWrap.querySelector(`input.preview-select-checkbox[data-block-id="${bid}"]`);
                            const blockEl = listWrap.querySelector(`.preview-block[data-block-id="${bid}"]`);
                            if (cb) { cb.disabled = true; cb.checked = true; }
                            if (blockEl) blockEl.style.opacity = '0.6';
                        });
                        acceptAllBtn.disabled = true;
                        acceptAllBtn.textContent = '已触发全部';
                        acceptSelectedBtn.disabled = true;
                    };
                    ops.appendChild(acceptAllBtn);

                    const acceptSelectedBtn = document.createElement('button');
                    acceptSelectedBtn.className = 'code-button';
                    acceptSelectedBtn.style.backgroundColor = '#4a6fa5';
                    acceptSelectedBtn.textContent = '接受选中';
                    acceptSelectedBtn.onclick = function () {
                        const checkedBoxes = Array.from(listWrap.querySelectorAll('input.preview-select-checkbox:checked'));
                        const toApply = checkedBoxes.map(cb => cb.getAttribute('data-block-id')).filter(Boolean).filter(bid => !executedSet.has(bid));
                        if (toApply.length === 0) {
                            alert('请先勾选要接受的项');
                            return;
                        }
                        toApply.forEach(bid => {
                            let planItem = null;
                            if (documentPlan) planItem = documentPlan.find(p => (p.blockId || p.id) === bid);
                            if (!planItem) planItem = { blockId: bid, action: 'insert_html', attributes: { previewHtml: previewHtmlMap[bid] } };
                            sendMessageToServer({ type: 'applyDocumentPlanItem', uuid: uuid, planItem: planItem });
                            executedSet.add(bid);
                            const blockEl = listWrap.querySelector('.preview-block[data-block-id="' + bid + '"]');
                            const cb = listWrap.querySelector(`input.preview-select-checkbox[data-block-id="${bid}"]`);
                            if (blockEl) blockEl.style.opacity = '0.6';
                            if (cb) { cb.disabled = true; cb.checked = true; }
                        });
                        // 如果所有项均已执行，禁用全部按钮
                        const remaining = orderedBlockIds.filter(id => !executedSet.has(id));
                        if (remaining.length === 0) {
                            acceptAllBtn.disabled = true;
                            acceptSelectedBtn.disabled = true;
                        }
                    };
                    ops.appendChild(acceptSelectedBtn);

                    header.appendChild(ops);
                    wrap.appendChild(header);

                    const previewArea = document.createElement('div');
                    previewArea.style.background = '#fff';
                    previewArea.style.padding = '8px';
                    previewArea.style.border = '1px solid #e6e6e6';
                    previewArea.style.borderRadius = '4px';
                    previewArea.style.display = 'flex';
                    previewArea.style.flexDirection = 'column';
                    previewArea.style.gap = '8px';
                    previewArea.style.maxHeight = '48vh';
                    previewArea.style.overflow = 'auto';

                    // 构建列表项（带复选框）
                    orderedBlockIds.forEach((bid, idx) => {
                        // 如果已执行则跳过（保险）
                        if (executedSet.has(bid)) return;

                        const frag = previewHtmlMap[bid];

                        const blockContainer = document.createElement('div');
                        blockContainer.className = 'preview-block';
                        blockContainer.style.padding = '8px';
                        blockContainer.style.border = '1px solid #f0f0f0';
                        blockContainer.style.borderRadius = '4px';
                        blockContainer.style.background = '#fff';
                        blockContainer.dataset.blockId = bid;

                        const blockRow = document.createElement('div');
                        blockRow.className = 'block-row';
                        blockRow.style.display = 'flex';
                        blockRow.style.alignItems = 'flex-start';
                        blockRow.style.gap = '8px';

                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.className = 'preview-select-checkbox';
                        checkbox.setAttribute('data-block-id', bid);
                        checkbox.title = '选中后，点击上方“接受选中”应用此块';
                        checkbox.checked = false;
                        checkbox.addEventListener('change', function () {
                            if (this.checked) blockContainer.style.boxShadow = '0 1px 6px rgba(74,111,165,0.12)';
                            else blockContainer.style.boxShadow = 'none';
                        });

                        const contentCol = document.createElement('div');
                        contentCol.style.flex = '1 1 auto';

                        const blockHeader = document.createElement('div');
                        blockHeader.style.display = 'flex';
                        blockHeader.style.justifyContent = 'space-between';
                        blockHeader.style.alignItems = 'center';
                        blockHeader.style.marginBottom = '6px';

                        const leftMeta = document.createElement('div');
                        leftMeta.style.fontSize = '12px';
                        leftMeta.style.color = '#444';
                        let noteText = '';
                        if (documentPlan) {
                            const item = documentPlan.find(p => (p.blockId || p.id) === bid);
                            if (item && item.note) noteText = item.note;
                        }
                        leftMeta.textContent = `${bid}${noteText ? ' — ' + noteText : ''}`;
                        blockHeader.appendChild(leftMeta);

                        const rightBtns = document.createElement('div');
                        rightBtns.style.display = 'flex';
                        rightBtns.style.gap = '6px';

                        const acceptBtn = document.createElement('button');
                        acceptBtn.className = 'code-button';
                        acceptBtn.style.backgroundColor = '#4CAF50';
                        acceptBtn.textContent = '接受';
                        acceptBtn.onclick = function () {
                            let planItem = null;
                            if (documentPlan) planItem = documentPlan.find(p => (p.blockId || p.id) === bid);
                            if (!planItem) planItem = { blockId: bid, action: 'insert_html', attributes: { previewHtml: previewHtmlMap[bid] } };
                            sendMessageToServer({ type: 'applyDocumentPlanItem', uuid: uuid, planItem: planItem });
                            executedSet.add(bid);
                            acceptBtn.disabled = true;
                            blockContainer.style.opacity = '0.6';
                            checkbox.disabled = true;
                            checkbox.checked = true;
                            const remaining = orderedBlockIds.filter(id => !executedSet.has(id));
                            if (remaining.length === 0) { acceptAllBtn.disabled = true; acceptSelectedBtn.disabled = true; }
                        };
                        rightBtns.appendChild(acceptBtn);
                        blockHeader.appendChild(rightBtns);

                        const contentDiv = document.createElement('div');
                        const text = previewHtmlMap[bid];
                        const looksLikeHtml = /<\/?[a-z][\s\S]*>/i.test(String(text || ''));
                        if (looksLikeHtml) contentDiv.innerHTML = text || '';
                        else contentDiv.innerHTML = renderPreviewFragment(text);

                        contentCol.appendChild(blockHeader);
                        contentCol.appendChild(contentDiv);

                        blockRow.appendChild(checkbox);
                        blockRow.appendChild(contentCol);

                        blockContainer.appendChild(blockRow);
                        listWrap.appendChild(blockContainer);
                    });

                    previewArea.appendChild(listWrap);
                    wrap.appendChild(previewArea);
                    container.appendChild(wrap);
                    wrap.scrollIntoView({ behavior: 'smooth', block: 'center' });

                } catch (err) {
                    console.error('showComparison error', err);
                }
            }

            //审阅修正建议列表
            window.showRevisions = function (responseUuid, revisions) {
                try {
                    let revs = [];
                    if (!revisions) revs = [];
                    else if (typeof revisions === 'string') {
                        try { revs = JSON.parse(revisions); } catch (e) { revs = []; }
                    } else revs = revisions;

                    const footer = document.getElementById('footer-' + responseUuid);
                    if (!footer) return;

                    // 隐藏 footer 的 reject 和 token计算、代码操作按钮
                    try {
                        const oldReject = footer.querySelector('.reject-btn');
                        if (oldReject) oldReject.style.display = 'none';
                        const tokenCount = footer.querySelector('.token-count');
                        if (tokenCount) tokenCount.style.display = 'none';
                        const codeButtons = footer.querySelector('.code-buttons');
                        if (codeButtons) codeButtons.style.display = 'none';

                    } catch (e) { }

                    // 移除已有容器
                    const exist = document.getElementById('revisions-' + responseUuid);
                    if (exist) exist.remove();

                    // 外层 wrapper，作为 footer 的内联 flex item，避免挤占右侧 token 显示
                    const footerWrapper = document.createElement('div');
                    footerWrapper.id = 'revisions-' + responseUuid;
                    footerWrapper.className = 'revisions-footer-wrapper';

                    // 顶部控件（插入到 footerWrapper 内部）
                    const controls = document.createElement('div');
                    controls.className = 'revisions-controls';

                    const btnAcceptAll = document.createElement('button');
                    btnAcceptAll.className = 'code-button';
                    btnAcceptAll.style.backgroundColor = '#4CAF50';
                    btnAcceptAll.textContent = '接受全部规则';
                    btnAcceptAll.onclick = function () {
                        // 顺序触发每个 accept 按钮
                        footerWrapper.querySelectorAll('.rev-accept-btn:not([disabled])').forEach(b => b.click());
                    };

                    const btnAcceptSelected = document.createElement('button');
                    btnAcceptSelected.className = 'code-button';
                    btnAcceptSelected.style.backgroundColor = '#4a6fa5';
                    btnAcceptSelected.textContent = '接受选中规则';
                    btnAcceptSelected.onclick = function () {
                        const checked = Array.from(footerWrapper.querySelectorAll('.rev-checkbox:checked'));
                        checked.forEach(chk => {
                            const idx = chk.getAttribute('data-idx');
                            const acceptBtn = footerWrapper.querySelector('.rev-accept-btn[data-idx="' + idx + '"]');
                            if (acceptBtn && !acceptBtn.disabled) acceptBtn.click();
                        });
                    };

                    controls.appendChild(btnAcceptAll);
                    controls.appendChild(btnAcceptSelected);
                    footerWrapper.appendChild(controls);

                    // 列表容器（垂直）
                    const listInner = document.createElement('div');
                    listInner.className = 'revisions-list-inner';

                    revs.forEach((item, idx) => {
                        const row = document.createElement('div');
                        row.className = 'revision-item';
                        row.id = `rev-${responseUuid}-${idx}`;

                        // checkbox
                        const cbWrap = document.createElement('div');
                        cbWrap.className = 'revision-checkbox';
                        const cb = document.createElement('input');
                        cb.type = 'checkbox';
                        cb.className = 'rev-checkbox';
                        cb.setAttribute('data-idx', idx);
                        cbWrap.appendChild(cb);

                        // summary: 包含 rule 和 note（更易读）
                        const summary = document.createElement('div');
                        summary.className = 'rev-summary';
                        const baseText = item.result || item.replaceWith || item.text || JSON.stringify(item);
                        const notePart = item.note ? (' — ' + item.note) : '';
                        summary.textContent = `#${idx+1} ${item.rule ? ('[' + item.rule + '] ') : ''}${baseText}${notePart}`;

                        // accept button
                        const accept = document.createElement('button');
                        accept.className = 'rev-accept-btn';
                        accept.textContent = '接受';
                        accept.setAttribute('data-idx', idx);
                        accept.onclick = function () {
                            // 禁用，避免重复触发
                            accept.disabled = true;
                            cb.disabled = true;
                            // payload
                            const payload = {
                                type: 'applyRevisionSegment',
                                uuid: responseUuid,
                                index: (item.index != null) ? item.index : idx,
                                action: item.action || 'replace',
                                matchText: item.matchText || '',
                                contextBefore: item.contextBefore || '',
                                contextAfter: item.contextAfter || '',
                                replaceWith: item.replaceWith || item.result || baseText
                            };

                            // 发送
                            sendMessageToServer(payload);

                            // 标记 UI 已接受
                            row.classList.add('rev-accepted');
                        };

                        row.appendChild(cbWrap);
                        row.appendChild(summary);
                        row.appendChild(accept);
                        listInner.appendChild(row);
                    });

                    footerWrapper.appendChild(listInner);

                    // 插入 footerWrapper 到 footer 左侧（不覆盖 token 区）
                    footer.insertBefore(footerWrapper, footer.firstChild);

                } catch (err) {
                    console.error('showRevisions error', err);
                }
            };

            // 兼容 fallback：从前端主动触发请求给后端
            window.applyRevisionAccept = function (responseUuid, globalIndex) {
                if (window.chrome && window.chrome.webview) {
                    window.chrome.webview.postMessage({ type: 'applyRevisionAccept', responseUuid: responseUuid, globalIndex: globalIndex });
                } else if (window.vsto) {
                    window.vsto.sendMessage({ type: 'applyRevisionAccept', responseUuid: responseUuid, globalIndex: globalIndex });
                }
            };

            // expose for debugging
            window._oa.showComparison = window.showComparison;
            window._oa.showRevisions = window.showRevisions;
        })();
    </script>
</body>
</html>